home *** CD-ROM | disk | FTP | other *** search
Text File | 1996-11-14 | 113.7 KB | 3,531 lines | [TEXT/MPS ] |
- /*------------------------------------------------------------------------------
-
- File: SamplePart.cpp
-
- Written by: Steve Smith
-
- Copyright: © 1995 by Apple Computer, Inc., all rights reserved.
-
- Description: SamplePart demonstrates the most basic functions and
- responsibilities of an OpenDoc™ leaf part.
-
-
- Demonstrates: The following recipes were used in implementing the
- SamplePart:
- 1. Open
- 2. Adding A Display Frame
- 3. Adding A Facet
- 4. Part Drawing
- 5. Refcounting Geometry
- 6. ViewTypes & Presentations
- 7. Display Frame 'ternalization
- 8. Part Init & Externalization
- 9. Part Init & partWrapper
- 10. Part Storage Model
- 11. Persistent Reference
- 12. RefCounting
- 13. Storage Unit
- 14. Activation
- 15. Basic Event Handling
- 16. Menus
- 17. Windows & Dialogs
- 18. Exception Handling
- 19. Memory Manager
- 20. Using Resources
- 21. Lazy Frame Internalization
- 22. Multiple Kind Support
-
-
- Notes: • For methods where it is necessary to call the parent class
- implementation, the calls are made from the SOM class. See
- som_SamplePart.cpp and the Class Reference to know whether
- you need to call the parent class from any method.
-
- ------------------------------------------------------------------------------*/
-
- // -- Compiler/Preprocessor Switches --
-
- #ifndef _COMPILERDEFS_
- #include "CompDefs.h"
- #endif
-
- // -- OpenDoc Utilities --
-
- #ifndef _EXCEPT_
- // Exceptions define several important macros (eg. CHECKENV)
- // which are used in the SOM method dispatch glue. If Except.h
- // is not included early enough, exceptions may not be thrown
- // correctly when returning from a SOM method with the "ev" parameter set.
- #include <Except.h>
- #endif
-
- // -- SamplePart Includes --
-
- #ifndef _SAMPLEPARTGLOBALS_
- #include "SamplePartGlobals.h"
- #endif
-
- #ifndef _SAMPLEPARTDEF_
- #include "SamplePartDef.h"
- #endif
-
- #ifndef _SAMPLEPARTUTILS_
- #include "SamplePartUtils.h"
- #endif
-
- #ifndef _SAMPLEPART_
- #include "SamplePart.h"
- #endif
-
- #ifndef _SAMPLECOLLECTIONS_
- #include "SampleCollections.h"
- #endif
-
- #ifndef _TEMPFOCUS_
- #include "TempFocus.h"
- #endif
-
- // -- OpenDoc Includes --
-
- #ifndef _ODTYPES_
- #include <ODTypes.h>
- #endif
-
- #ifndef SOM_ODPart_xh
- #include <Part.xh>
- #endif
-
- #ifndef SOM_ODFacet_xh
- #include <Facet.xh>
- #endif
-
- #ifndef SOM_ODFrame_xh
- #include <Frame.xh>
- #endif
-
- #ifndef SOM_ODFrameFacetIterator_xh
- #include <FrFaItr.xh>
- #endif
-
- #ifndef SOM_ODArbitrator_xh
- #include <Arbitrat.xh>
- #endif
-
- #ifndef SOM_Module_OpenDoc_Foci_defined
- #include <Foci.xh>
- #endif
-
- #ifndef SOM_ODShape_xh
- #include <Shape.xh>
- #endif
-
- #ifndef SOM_Module_OpenDoc_StdProps_defined
- #include <StdProps.xh>
- #endif
-
- #ifndef SOM_Module_OpenDoc_StdTypes_defined
- #include <StdTypes.xh>
- #endif
-
- #ifndef SOM_Module_OpenDoc_StdDefs_defined
- #include <StdDefs.xh>
- #endif
-
- #ifndef SOM_Module_OpenDoc_Commands_defined
- #include <CmdDefs.xh>
- #endif
-
- #ifndef SOM_ODDraft_xh
- #include <Draft.xh>
- #endif
-
- #ifndef SOM_ODStorageUnit_xh
- #include <StorageU.xh>
- #endif
-
- #ifndef SOM_ODStorageUnitView_xh
- #include <SUView.xh>
- #endif
-
- #ifndef SOM_ODTransform_xh
- #include <Trnsform.xh>
- #endif
-
- #ifndef SOM_ODFocusSet_xh
- #include <FocusSet.xh>
- #endif
-
- #ifndef SOM_ODMenuBar_xh
- #include <MenuBar.xh>
- #endif
-
- #ifndef SOM_ODWindow_xh
- #include <Window.xh>
- #endif
-
- #ifndef SOM_ODWindowState_xh
- #include <WinStat.xh>
- #endif
-
- #ifndef SOM_ODCanvas_xh
- #include <Canvas.xh>
- #endif
-
- #ifndef SOM_ODSession_xh
- #include <ODSessn.xh>
- #endif
-
- // -- OpenDoc Utilities --
-
- #ifndef _ITEXT_
- #include <IText.h>
- #endif
-
- #ifndef _FOCUSLIB_
- #include <FocusLib.h>
- #endif
-
- #ifndef _BNDNSUTL_
- #include <BndNSUtl.h>
- #endif
-
- #ifndef _DLOGUTIL_
- #include <DlogUtil.h>
- #endif
-
- #ifndef _ISOSTR_
- #include <ISOStr.h>
- #endif
-
- #ifndef _ODDEBUG_
- #include <ODDebug.h>
- #endif
-
- #ifndef _ODMEMORY_
- #include <ODMemory.h>
- #endif
-
- #ifndef _ODUTILS_
- #include <ODUtils.h>
- #endif
-
- #ifndef _STORUTIL_
- #include <StorUtil.h>
- #endif
-
- #ifndef _STDTYPIO_
- #include <StdTypIO.h>
- #endif
-
- #ifndef _TEMPITER_
- #include <TempIter.h>
- #endif
-
- #ifndef _TEMPOBJ_
- #include <TempObj.h>
- #endif
-
- #ifndef _USERSRCM_
- #include <UseRsrcM.h>
- #endif
-
- #ifndef _WINUTILS_
- #include <WinUtils.h>
- #endif
-
- // -- Macintosh Includes --
-
- #ifndef __ERRORS__
- #include <Errors.h>
- #endif
-
- #ifndef __RESOURCES__
- #include <Resources.h>
- #endif
-
- #ifndef __DIALOGS__
- #include <Dialogs.h>
- #endif
-
- #ifndef __TOOLUTILS__
- #include <ToolUtils.h>
- #endif
-
- #ifndef __ICONS__
- #include <Icons.h>
- #endif
-
- #ifndef __QUICKDRAW__
- #include <Quickdraw.h>
- #endif
-
- #ifndef __GXMATH__
- #include <GXMath.h>
- #endif
-
- #ifndef __DRAG__
- #include <Drag.h>
- #endif
-
- //ForTSMTE
- #ifndef __tsmUtl__
- #include "tsmUtl.h"
- #endif
-
- #pragma segment SamplePart
-
- //==============================================================================
- // SamplePart
- //==============================================================================
-
- //------------------------------------------------------------------------------
- // Method: Constructor
- // Origin: SamplePart
- //
- // Description: This is the C++ class constructor.
- //
- // Warnings: You are not allowed to throw an exception from this method.
- //------------------------------------------------------------------------------
-
- SamplePart::SamplePart()
- {
- SOM_Trace("SamplePart","Constructor");
-
- fDisplayFrames = kODNULL;
- fDirty = kODFalse;
- fSelf = kODNULL;
- fReadOnlyStorage = kODFalse;
-
- fGlobalsInited = kODFalse;
- }
-
- //------------------------------------------------------------------------------
- // Method: Destructor
- // Origin: SamplePart
- //
- // Description: This is the C++ class destructor.
- //
- // Warnings: You are not allowed to throw an exception from this method.
- //------------------------------------------------------------------------------
-
- SamplePart::~SamplePart()
- {
- SOM_Trace("SamplePart","Destructor");
- }
-
- //==============================================================================
- #pragma mark • Initialization •
- //==============================================================================
-
- //------------------------------------------------------------------------------
- // Method: InitPart
- // Origin: ODPart
- //
- // Description: This method is called when a new instance of this part is being
- // created. The part should prepare itself to run.
- //
- // Parent: The part's parent class was called before this method was
- // dispatched to (see som_SamplePart.cpp).
- //
- // Warning: It is not appropriate to require user interaction while
- // stationery is being created. Do not present the user with error
- // dialogs or splash screens from this method.
- //------------------------------------------------------------------------------
-
- void SamplePart::InitPart( Environment* ev,
- ODStorageUnit* storageUnit,
- ODPart* partWrapper )
- {
- SOM_Trace("SamplePart","InitPart");
-
- TRY
- // To allow editor swapping (translation) at runtime, OpenDoc requires
- // that we pass in a "reference" to ourselves when interacting with the
- // API (eg. WindowState::RegisterWindow(), Dispatcher::RegisterIdle, etc).
- // The "partWrapper" passed to us here and in InitPartFromStorage is the
- // "reference" OpenDoc is asking us to use.
- fSelf = partWrapper;
-
- // We are being created, either as part of generating stationery or
- // by some editor instantiating the part, so the destination storage
- // must be writeable.
- fReadOnlyStorage = kODFalse;
-
- // Call the common initialization code to get set up.
- this->Initialize(ev);
-
- // Since we have just been created, our state/content info has
- // never been written out, so setting our "dirty" flag will
- // give us a chance to do that.
- this->SetDirty(ev);
-
- CATCH_ALL
- // Clean up will occur in the destructor which will be called
- // shortly after we return the error.
- RERAISE;
- ENDTRY
- }
-
- //------------------------------------------------------------------------------
- // Method: InitPartFromStorage
- // Origin: ODPart
- //
- // Description: This method is called when a document/stationery is being opened
- // or when the part is internalized by its containing part. The
- // part should merely read in the saved state/content and
- // initialize itself. The part must not alter its storage unit;
- // otherwise, the "Save" menu item becomes enabled without the user
- // actually having made a change to the document.
- //
- // Parent: The part's parent class was called before this method was
- // dispatched to (see som_SamplePart.cpp).
- //------------------------------------------------------------------------------
-
- void SamplePart::InitPartFromStorage( Environment* ev,
- ODStorageUnit* storageUnit,
- ODPart* partWrapper )
- {
- SOM_Trace("SamplePart","InitPartFromStorage");
-
- TRY
- // To allow editor swapping (translation) at runtime, OpenDoc requires
- // that we pass in a "reference" to ourselves when interacting with the
- // API (eg. WindowState::RegisterWindow(), Dispatcher::RegisterIdle, etc).
- // The "partWrapper" passed to us here and in InitPart is the
- // "reference" OpenDoc is asking us to use.
- fSelf = partWrapper;
-
- // Are we being opened from a read-only draft? If so, we cannot
- // write anything back out to our storage unit.
- fReadOnlyStorage = ( ODGetDraft(ev,storageUnit)->
- GetPermissions(ev) < kODDPSharedWrite );
-
- // Call the common initialization code to get set up.
- this->Initialize(ev);
-
- // Read in the state the part was in when it was last Externalized.
- // This allows the part to present the same "environment" the user
- // had the part set up in the last time it was edited.
- this->InternalizeStateInfo(ev, storageUnit);
-
- // Read in the contents for your part editor.
- this->InternalizeContent(ev, storageUnit);
-
- CATCH_ALL
- // Clean up will occur in the destructor which will be called
- // shortly after we return the error.
- RERAISE;
- ENDTRY
- }
-
- //------------------------------------------------------------------------------
- // Method: Initialize
- // Origin: SamplePart
- //
- // Description: This method is called during the initialization of the part. The
- // method is used to initialize all fields of the part and to
- // convert ISO types to tokens for faster comparisons throughout
- // the code.
- //
- // If an exception is thrown in this method, it wil be propogated
- // back to OpenDoc which will call our ReleaseAll() method and the
- // class destructor. All memory allocated here will be cleaned up
- // in the ReleaseAll() method.
- //------------------------------------------------------------------------------
-
- void SamplePart::Initialize( Environment* ev )
- {
- SOM_Trace("SamplePart","Initialize");
-
- // Grab a reference to the Session object. This is merely for
- // convenience.
- ODSession* session = ODGetSession(ev,fSelf);
-
- // Initialize the Binding Name Space Utilities (new to version 1.1)
- InitBindingNamespaceUtils(session);
-
- // Create a list to keep track of the frames we are being
- // displayed in. Used for part maintenance (ie. Purging memory).
- fDisplayFrames = new CList;
-
- // First check to see if the library's global variables have
- // been initialized (meaning another part instantiation is already
- // running).
-
- if ( gGlobalsUsageCount == 0 )
- {
- // Create our globals space. We store the globals in a struct so
- // that we can put them in temp mem. Otherwise, CFM loads the globals
- // with the data fragment of a CFM library in the application heap.
- gGlobals = new SamplePartGlobals;
-
- // It is required that parts instantiate their menu bars from
- // the base OpenDoc menu bar. This maintains consistency in the
- // default menu items and their placement.
- // Since the object is a copy, we can add and subtract menus and
- // items without affecting other running parts.
- gGlobals->fMenuBar = session->GetWindowState(ev)->CopyBaseMenuBar(ev);
-
- // We will be using the following foci (shared resources) in this
- // part. For convenience, we tokenize the values here and store
- // them for equivalence tests in the activation methods.
- gGlobals->fSelectionFocus = session->Tokenize(ev, kODSelectionFocus);
- gGlobals->fMenuFocus = session->Tokenize(ev, kODMenuFocus);
- gGlobals->fModalFocus = session->Tokenize(ev, kODModalFocus);
- gGlobals->fKeyFocus = session->Tokenize(ev, kODKeyFocus); //ForTSMTE
-
- // Also for convenience, we tokenize our part's main presentation
- // and the standard view types.
- gGlobals->fMainPresentation = session->Tokenize(ev, kMainPresentation);
-
- gGlobals->fFrameView = session->Tokenize(ev, kODViewAsFrame);
- gGlobals->fLargeIconView = session->Tokenize(ev, kODViewAsLargeIcon);
- gGlobals->fSmallIconView = session->Tokenize(ev, kODViewAsSmallIcon);
- gGlobals->fThumbnailView = session->Tokenize(ev, kODViewAsThumbnail);
-
- // Lastly, we will package the menu and selection focus
- // so that we can request the "set" at activation time.
- gGlobals->fUIFocusSet = session->GetArbitrator(ev)->CreateFocusSet(ev);
- gGlobals->fUIFocusSet->Add(ev, gGlobals->fMenuFocus);
- gGlobals->fUIFocusSet->Add(ev, gGlobals->fSelectionFocus);
- gGlobals->fUIFocusSet->Add(ev, gGlobals->fKeyFocus); //ForTSMTE
-
- // Determine what Script/Language the part is localized for.
- // This is important/necessary for creating OpenDoc's text objects.
- GetEditorScriptLanguage(ev, &gGlobals->fEditorsScript, &gGlobals->fEditorsLanguage);
-
- // The first client of the global variables is running.
- gGlobalsUsageCount = 1;
- fGlobalsInited = kODTrue;
- }
- else
- // If the globals have been initialized, we just bump the "usage" count so
- // that we know how many part instances are using them.
- {
- gGlobalsUsageCount++;
- fGlobalsInited = kODTrue;
- }
-
- //ForTSMTE
- fTERec.fText[0] = 0;
- fTERec.fTEHandle = kODNULL;
- tsmCheck(&fTERec);
- }
-
- //==============================================================================
- #pragma mark • Storage •
- //==============================================================================
-
- //------------------------------------------------------------------------------
- // Method: Release
- // Origin: ODPart
- //
- // Description: This method is called each time an object releases a reference
- // to the part. If the refcount falls to 0, the part should
- // release the fSelf part reference.
- //
- // Parent: The part's parent class was called before this method was
- // dispatched to (see som_SamplePart.cpp).
- //
- // Warning: If the part releases any other object when the refcount falls to
- // zero, it will need to override the Acquire method so
- // that the object can be referenced again if the parts refcount
- // should be incremented before it is deleted.
- //------------------------------------------------------------------------------
-
- void SamplePart::Release( Environment* ev )
- {
- SOM_Trace("SamplePart","Release");
-
- if ( fSelf->GetRefCount(ev) == 0 )
- ODGetDraft(ev,fSelf)->ReleasePart(ev,fSelf);
- }
-
- //------------------------------------------------------------------------------
- // Method: ReleaseAll
- // Origin: ODPart
- //
- // Description: This method is called just prior to the part being deleted by
- // the Draft. The part must release all references to all
- // refcounted objects it has stored internally; not doing so, will
- // cause an "invalid ref count" exception/error at some later time.
- //
- // Parent: The part's parent class will be called after this method
- // returns (see som_SamplePart.cpp).
- //------------------------------------------------------------------------------
-
- void SamplePart::ReleaseAll( Environment* ev )
- {
- SOM_Trace("SamplePart","ReleaseAll");
-
- TRY
- // If the last part instance using the globals is released,
- // we need to clean up and delete the globals.
-
- if ( fGlobalsInited && (--gGlobalsUsageCount == 0) )
- {
- // Release the menubar.
- ODReleaseObject(ev, gGlobals->fMenuBar);
-
- // But first, we need to delete the objects we created
- // and stored in the globals struct.
- ODDeleteObject(gGlobals->fUIFocusSet);
-
- // Release the thumbnail (PICT) resource.
- if ( gGlobals->fThumbnail )
- {
- ReleaseResource(gGlobals->fThumbnail);
- gGlobals->fThumbnail = kODNULL;
- }
-
- // Now, clean up the globals struct.
- ODDeleteObject(gGlobals);
- }
-
- // Remove and release our display frames.
- if ( fDisplayFrames )
- {
- CListIterator fiter(fDisplayFrames);
- for ( CFrameProxy* proxy = (CFrameProxy*) fiter.First();
- fiter.IsNotComplete(); proxy = (CFrameProxy*) fiter.Next() )
- {
- // Delete the proxy object and its contents. The frame's
- // refcount will be decremented in the proxy destructor.
- fiter.RemoveCurrent();
- delete proxy;
- }
-
- // Delete the display frame collection.
- ODDeleteObject(fDisplayFrames);
- }
-
- CATCH_ALL
- // If something goes wrong while we are cleaning up, we must
- // let the Draft now because there may be some refcounted objects
- // which did not get released. Not to mention, possible memory
- // leaks.
- RERAISE;
- ENDTRY
- }
-
- //------------------------------------------------------------------------------
- // Method: Purge
- // Origin: ODPart
- //
- // Description: This method is called when the OpenDoc requires more memory for
- // allocating objects and just before a part is deleted. The part
- // should free up as much memory as it can.
- //
- // The part determines which views are being "used" in its display
- // frames. The resources for the unused view types are then purged.
- //------------------------------------------------------------------------------
-
- ODSize SamplePart::Purge( Environment* ev,
- ODSize /*size*/ )
- {
- SOM_Trace("SamplePart","Purge");
-
- // Purge is called during the creation of stationery. However,
- // we have not created our internal display frames list, so
- // trying to iterate over it would be fatal.
- if ( fDisplayFrames == kODNULL ) return 0;
-
- ODSize bytesFreed = 0;
- ODBoolean usingThumbnail = kODFalse;
-
- // Iterate over the frames we are displayed through and determine which
- // view types are currently in use.
-
- CListIterator fiter(fDisplayFrames);
- for ( CFrameProxy* proxy = (CFrameProxy*) fiter.First();
- fiter.IsNotComplete(); proxy = (CFrameProxy*) fiter.Next() )
- {
- // If the display frame is real (has been "connected" or was "added")
- // get its view type; otherwise, ignore it.
- if ( proxy->FrameIsLoaded(ev) )
- {
- ODTypeToken frameView = proxy->GetFrame(ev)->GetViewType(ev);
-
- if ( frameView == gGlobals->fThumbnailView )
- usingThumbnail = kODTrue;
-
- // Release the frame reference, but don't get rid of the
- // proxy object because we're not done with the frame. If
- // all parts release their references the frame will be
- // purged from memory.
- proxy->Purge(ev);
- }
- }
-
- // Based on the usage of the supported view types, free up as much
- // memory as possible.
-
- if ( !usingThumbnail && (gGlobals->fThumbnail != kODNULL) )
- {
- bytesFreed += (ODSize) ODGetHandleSize(gGlobals->fThumbnail);
- ReleaseResource(gGlobals->fThumbnail);
- gGlobals->fThumbnail = kODNULL;
- }
-
- return bytesFreed;
- }
-
- //------------------------------------------------------------------------------
- // Method: InternalizeStateInfo
- // Origin: SamplePart
- //
- // Description: This method is used to read in "state" information for the part.
- // This is information related to the workings of the part editor,
- // not the content.
- //
- // The part writes out a list of weak references to its display
- // frames. This allows the part to reuse the same display frames
- // each time the document is opened. Those references are read
- // back in and validated here.
- //
- // Note: The function StorageUnitGetValue simplifies the use of
- // ODByteArrary, which is required the StorageUnit interface. Look
- // in StorUtil.h/cpp for an example of using the ODByteArray struct.
- //------------------------------------------------------------------------------
-
- void SamplePart::InternalizeStateInfo( Environment* ev,
- ODStorageUnit* storageUnit )
- {
- SOM_Trace("SamplePart","InternalizeStateInfo");
-
- ODStorageUnitRef weakRef;
- ODULong size;
-
- // Internalize the part's display frame list.
-
- if ( storageUnit->Exists(ev, kODPropDisplayFrames, kODWeakStorageUnitRefs, 0) )
- {
- storageUnit->Focus(ev, kODPropDisplayFrames, kODPosUndefined,
- kODWeakStorageUnitRefs, 0, kODPosUndefined);
-
- size = storageUnit->GetSize(ev);
- storageUnit->SetOffset(ev, 0);
-
- for ( ODULong offset = 0; offset < size; offset += kODStorageUnitRefSize )
- {
- TRY
- StorageUnitGetValue(storageUnit, ev, kODStorageUnitRefSize, (ODPtr)&weakRef);
-
- if ( storageUnit->IsValidStorageUnitRef(ev, weakRef) )
- {
- // We lazily internalize our display frames, meaning we don't "get"
- // the frame until we absolutely need it. This reduces the time
- // to internalize the part and the amount of memory needed.
-
- // Convert the reference into a runtime id.
- ODID frameID = storageUnit->GetIDFromStorageUnitRef(ev, weakRef);
-
- // Create a proxy class to support the lazy internalization.
- CFrameProxy* proxy = new CFrameProxy;
- proxy->InitFrameProxy(frameID, ODGetDraft(ev,storageUnit));
-
- // Add the proxy to the display frame collection.
- fDisplayFrames->Add(proxy);
- }
- CATCH_ALL
- // consume exception
- ENDTRY
- }
- }
- }
-
- //------------------------------------------------------------------------------
- // Method: InternalizeContent
- // Origin: SamplePart
- //
- // Description: This method is called during initialization of the part from an
- // existing document. The content of the part should be read in.
- //
- // The part has no intrinsic content, so the part does nothing.
- // The method is here for completeness.
- //------------------------------------------------------------------------------
-
- void SamplePart::InternalizeContent( Environment* ev,
- ODStorageUnit* /*storageUnit*/ )
- {
- SOM_Trace("SamplePart","InternalizeContent");
-
- }
-
- //------------------------------------------------------------------------------
- // Method: CloneInto
- // Origin: ODPart
- //
- // Description: This method is called during cloning, typically during data
- // interchange operations (eg. Cut/Paste). The part should
- // write out its current state and content.
- //
- // Parent: The part's parent class was called before this method was
- // dispatched to (see som_SamplePart.cpp).
- //------------------------------------------------------------------------------
-
- void SamplePart::CloneInto( Environment* ev,
- ODDraftKey key,
- ODStorageUnit* destinationSU,
- ODFrame* initiatingFrame )
- {
- SOM_Trace("SamplePart","CloneInto");
-
- // We must first verify that we've never written to this storage unit.
- // If we have, we should do nothing, otherwise we need to write out
- // the current state of the part content.
-
- if ( destinationSU->Exists(ev, kODPropContents, kSamplePartKind, 0) == kODFalse )
- {
- // Add the properties we need to successfully externalize
- // ourselves into the destination storage unit.
- this->CheckAndAddProperties(ev, destinationSU);
-
- // Write out the part's state information.
- this->ExternalizeStateInfo(ev, destinationSU, key, initiatingFrame);
-
- // Write out the part's content.
- this->ExternalizeContent(ev, destinationSU, key, initiatingFrame);
- }
- }
-
- //------------------------------------------------------------------------------
- // Method: Externalize
- // Origin: ODPart
- //
- // Description: This method is called when the user saves the document. The part
- // should write out its state and content if changes have occurred
- // and if our storage is writeable.
- //
- // Parent: The part's parent class was called before this method was
- // dispatched to (see som_SamplePart.cpp).
- //------------------------------------------------------------------------------
-
- void SamplePart::Externalize( Environment* ev )
- {
- SOM_Trace("SamplePart","Externalize");
-
- TRY
- if ( fDirty && !fReadOnlyStorage )
- {
- // Get our storage unit.
- ODStorageUnit* storageUnit = fSelf->GetStorageUnit(ev);
-
- // Verify that the storage unit has the appropriate properties
- // and values to allow us to run. If not, add them.
- this->CheckAndAddProperties(ev, storageUnit);
-
- // Verify that there are no "bogus" values in the Content
- // property.
- this->CleanseContentProperty(ev, storageUnit);
-
- // Write out the part's state information.
- this->ExternalizeStateInfo(ev, storageUnit, kODNULLKey, kODNULL);
-
- // Write out the part's content.
- this->ExternalizeContent(ev, storageUnit, kODNULLKey, kODNULL);
-
- // Flag our part as no longer being dirty.
- fDirty = kODFalse;
- }
- CATCH_ALL
- // Alert the user of the problem.
- this->DoDialogBox(ev, kODNULL, kErrorBoxID, kErrExternalizeFailed);
- // Change the exception value, so the DocShell doesn't display an
- // error dialog.
- SetErrorCode(kODErrAlreadyNotified);
- // Alert the caller.
- RERAISE;
- ENDTRY
- }
-
- //------------------------------------------------------------------------------
- // Method: ExternalizeKinds
- // Origin: ODPart
- //
- // Description: This method is called when the user wants to save the document
- // with multiple representations of the data. This is especially
- // useful for increasing the portability of documents
- // cross-platform.
- //
- // A part should verify each kind is valid, that it exists in
- // the content property in the correct order, and write the data.
- //
- // Note: For parts which support only on kind, the code can simplified.
- // In this case, it is not necessary to iterate over the kindset
- // because you must, at least, write your preferred kind. The code
- // is shown this way to better illustrate the recipe; it is not
- // wrong, it just does more than it needs to.
- //------------------------------------------------------------------------------
-
- void SamplePart::ExternalizeKinds( Environment* ev,
- ODTypeList* kindset )
- {
- if ( !fReadOnlyStorage )
- {
- ODBoolean preferredKindWritten = kODFalse;
-
- // Get our storage unit.
- ODStorageUnit* storageUnit = fSelf->GetStorageUnit(ev);
-
- // Verify that the storage unit has the appropriate properties
- // and values to allow us to run. If not, add them.
- this->CheckAndAddProperties(ev, storageUnit);
-
- // Verify that there are no "bogus" values in the Content
- // property.
- this->CleanseContentProperty(ev, storageUnit);
-
- // Iterate over the kindset and write out the content types
- // that we support.
- TempODTypeListIterator tliter(ev, kindset);
- for ( ODType kind = tliter.First(); tliter.IsNotComplete();
- kind = tliter.Next() )
- {
- // Check to see if this is a kind we support. If so, write it.
- if ( ODISOStrCompare(kind, kSamplePartKind) == 0 )
- {
- // Write out the part's content.
- this->ExternalizeContent(ev, storageUnit, kODNULLKey, kODNULL);
- // This is our preferrend kind so we don't need to write it again.
- // Part editors with more than one kind need to test each kind
- // against the preferred kind to make sure it's been written.
- preferredKindWritten = kODTrue;
- }
- }
-
- // Write out the part's state information.
- this->ExternalizeStateInfo(ev, storageUnit, kODNULLKey, kODNULL);
-
- // Even if the kind set contains no types we support, we must at least
- // write out our current "preferred" kind.
- if ( preferredKindWritten == kODFalse )
- {
- // Write out the part's preferred content kind, which, for SamplePart,
- // is the only kind.
- this->ExternalizeContent(ev, storageUnit, kODNULLKey, kODNULL);
- }
- }
- }
-
- //------------------------------------------------------------------------------
- // Method: ChangeKind
- // Origin: ODPart
- //
- // Description: This method is called when the changes the part's primary kind
- // and/or when the part editor is switched via the Info dialog.
- //
- // The editor should record the new "preferred" kind and change the
- // UI, if necessary, to allow editing of that kind. Don't write the
- // properties/values/data until the Externalize is called.
- //------------------------------------------------------------------------------
-
- void SamplePart::ChangeKind( Environment* ev,
- ODType kind )
- {
- // SamplePart only has one kind, but we need to make sure the "Preferred Kind"
- // property has the correct value.
- if ( ODISOStrCompare(kind, kSamplePartKind) == 0 )
- {
- // Get our storage unit.
- ODStorageUnit* storageUnit = fSelf->GetStorageUnit(ev);
-
- TRY
- // Write out the users preferred kind.
- ODSetISOStrProp(ev, storageUnit, kODPropPreferredKind, kODISOStr, kSamplePartKind);
-
- // Changing our kind dirties our content.
- this->SetDirty(ev);
-
- // Immediately externalize ourselves in the "new" format.
- this->Externalize(ev);
- CATCH_ALL
- // Remove the property and value if something went wrong.
- ODSURemoveProperty(ev, storageUnit, kODPropPreferredKind);
- ENDTRY
- }
- else
- THROW(kODErrInvalidValueType);
- }
-
- //------------------------------------------------------------------------------
- // Method: ExternalizeStateInfo
- // Origin: SamplePart
- //
- // Description: This method is called during externalization of the part. The
- // current "state" of the part should be written out. This "state"
- // information may be lost during Data Interchange operations, so
- // the part needs to recover gracefully if information is missing
- // or incomplete.
- //
- // Note: The function StorageUnitSetValue is a macro which simplifies
- // the use of ODByteArrary, which is required by the StorageUnit
- // interface. Look in StorUtil.h/cpp for an example of using the
- // ODByteArray struct.
- //------------------------------------------------------------------------------
-
- void SamplePart::ExternalizeStateInfo( Environment* ev,
- ODStorageUnit* storageUnit,
- ODDraftKey key,
- ODFrame* scopeFrame )
- {
- SOM_Trace("SamplePart","ExternalizeStateInfo");
-
- ODStorageUnitRef weakRef;
- ODID frameID;
- ODID scopeFrameID = ( scopeFrame ? scopeFrame->GetID(ev) : kODNULLID );
- ODDraft* fromDraft = ODGetDraft(ev,fSelf);
-
- // Externalize the part's display frame list.
-
- storageUnit->Focus(ev, kODPropDisplayFrames, kODPosUndefined,
- kODWeakStorageUnitRefs, 0, kODPosUndefined);
-
- // Persistent object references are stored in a side table, rather than
- // in the property/value stream. Thus, deleting the contents of a value
- // will not "delete" the references previously written to that value. To
- // completely "delete" all references written to the value, we must
- // remove the value and add it back.
- storageUnit->Remove(ev);
- storageUnit->AddValue(ev, kODWeakStorageUnitRefs);
-
- CListIterator fiter(fDisplayFrames);
- for ( CFrameProxy* proxy = (CFrameProxy*) fiter.First();
- fiter.IsNotComplete(); proxy = (CFrameProxy*) fiter.Next() )
- {
- // Get the ID of the frame we are going to weakly reference.
- frameID = proxy->GetID();
-
- // If a draft key exists, then we are being cloned to another draft.
- // We must "weak" clone our display frame and reference the cloned
- // frame. The part re-uses the frameID variable so there aren't two
- // different GetWeakStorageUnitRef calls.
- if ( key )
- frameID = fromDraft->WeakClone(ev, key, frameID, kODNULLID, scopeFrameID);
-
- // Write out weak references to each of the part's display frames.
- storageUnit->GetWeakStorageUnitRef(ev, frameID, weakRef);
- TRY
- StorageUnitSetValue(storageUnit, ev, kODStorageUnitRefSize, (ODPtr)&weakRef);
- CATCH_ALL
- // consume the exception
- ENDTRY
- }
- }
-
- //------------------------------------------------------------------------------
- // Method: ExternalizeContent
- // Origin: SamplePart
- //
- // Description: This method is called during exteralization of the part. The
- // content of the part should be written out.
- //
- // The part has no intrinsic content, so the part does nothing.
- // The method is here for completeness.
- //------------------------------------------------------------------------------
-
- void SamplePart::ExternalizeContent( Environment* ev,
- ODStorageUnit* /*storageUnit*/,
- ODDraftKey /*key*/,
- ODFrame* /*scopeFrame*/ )
- {
- SOM_Trace("SamplePart","ExternalizeContent");
-
- // You would write out your part's content after focusing to your
- // content property.
- }
-
- //------------------------------------------------------------------------------
- // Method: CleanseContentProperty
- // Origin: SamplePart
- //
- // Description: This method is called during exteralization of the part so that
- // the part can remove any value in the content property
- // that it cannot "accurately" write to.
- //
- // Note: "Additional" values will be added to a part's content property
- // during Drag & Drop operations.
- //------------------------------------------------------------------------------
-
- void SamplePart::CleanseContentProperty( Environment* ev,
- ODStorageUnit* storageUnit )
- {
- SOM_Trace("SamplePart","CleanseContentProperty");
-
- ODULong numValues;
- ODULong index;
-
- storageUnit->Focus(ev, kODPropContents, kODPosUndefined,
- kODNULL, 0, kODPosAll);
-
- numValues = storageUnit->CountValues(ev);
-
- for (index = numValues; index >= 1; index--)
- {
- // Index from 1 to n through the values.
- storageUnit->Focus(ev, kODPropContents, kODPosUndefined,
- kODNULL, index, kODPosUndefined);
-
- // Get the ISO type name for the value. The temp object
- // will automatically delete the returned value when this
- // scope is exited.
- TempODValueType value = storageUnit->GetType(ev);
-
- // If the value type is not one we support, remove it.
- if ( ODISOStrCompare(value, kSamplePartKind) != 0 )
- storageUnit->Remove(ev);
- }
- }
-
- //------------------------------------------------------------------------------
- // Method: CheckAndAddProperties
- // Origin: SamplePart
- //
- // Description: This method is called during externalization of the part to
- // verify that all the properties needed to persistently represent
- // the current running state of the part.
- //
- // The part adds the default content property, a preferred editor
- // property (to aid in part binding), and a display frames
- // property.
- //
- // Note: The function StorageUnitSetValue is a macro which simplifies
- // the use of ODByteArrary, which is required the StorageUnit
- // interface. Look in StorUtil.h/cpp for an example of using the
- // ODByteArray struct.
- //------------------------------------------------------------------------------
-
- void SamplePart::CheckAndAddProperties( Environment* ev,
- ODStorageUnit* storageUnit )
- {
- SOM_Trace("SamplePart","CheckAndAddProperties");
-
- // Create our content property and preferred content property kind.
-
- if ( !storageUnit->Exists(ev, kODPropContents, kODNULL, 0) )
- storageUnit->AddProperty(ev, kODPropContents);
- if ( !storageUnit->Exists(ev, kODPropContents, kSamplePartKind, 0) )
- {
- storageUnit->Focus(ev, kODPropContents, kODPosUndefined, kODNULL, 0, kODPosAll);
- storageUnit->AddValue(ev, kSamplePartKind);
- }
-
- // Since we are setting up the preferred kind property, we just write
- // out our default "kind" for the editor. We can write out the user
- // chosen kind in the ExternalizeStateInfo method.
-
- if ( !storageUnit->Exists(ev, kODPropPreferredKind, kODISOStr, 0) )
- {
- TRY
- ODSetISOStrProp(ev, storageUnit, kODPropPreferredKind, kODISOStr, kSamplePartKind);
- CATCH_ALL
- // Remove the property and value if something went wrong.
- ODSURemoveProperty(ev, storageUnit, kODPropPreferredKind);
- ENDTRY
- }
-
- // Add our display frame list.
-
- if ( !storageUnit->Exists(ev, kODPropDisplayFrames, kODNULL, 0) )
- storageUnit->AddProperty(ev, kODPropDisplayFrames);
- if ( !storageUnit->Exists(ev, kODPropDisplayFrames, kODWeakStorageUnitRefs, 0) )
- {
- storageUnit->Focus(ev, kODPropDisplayFrames, kODPosUndefined, kODNULL, 0, kODPosAll);
- storageUnit->AddValue(ev, kODWeakStorageUnitRefs);
- }
- }
-
- //------------------------------------------------------------------------------
- // Method: SetDirty
- // Origin: SamplePart
- //
- // Description: This method is called by the part when the content or state of
- // the part has been modified by the user and the "Save" menu item
- // should be enabled.
- //------------------------------------------------------------------------------
-
- void SamplePart::SetDirty( Environment* ev )
- {
- SOM_Trace("SamplePart","SetDirty");
-
- // There is no need to repeatedly tell the draft we have changed;
- // once is sufficient.
- if ( !fDirty && !fReadOnlyStorage )
- {
- fDirty = kODTrue;
- ODGetDraft(ev,fSelf)->SetChangedFromPrev(ev);
- }
- }
-
- //------------------------------------------------------------------------------
- // Method: ReadPartInfo
- // Origin: ODPart
- //
- // Description: When a frame is being internalized by the Draft, it will ask the
- // owner (part) to read in its info annotation on the frame.
- //
- // The part uses a C++ helper class to encapsulate the information
- // we store with each frame, so we let it internalize itself from
- // the storage unit view.
- //------------------------------------------------------------------------------
-
- ODInfoType SamplePart::ReadPartInfo( Environment* ev,
- ODFrame* frame,
- ODStorageUnitView* storageUnitView )
- {
- SOM_Trace("SamplePart","ReadPartInfo");
-
- CFrameInfo* frameInfo = new CFrameInfo(ODGetSession(ev,fSelf));
-
- TRY
- // Ask the info class to internalize itself.
- frameInfo->InitFromStorage(ev, storageUnitView);
- CATCH_ALL
- // Clean up the allocated memory.
- ODDeleteObject(frameInfo);
- // Alert the caller.
- RERAISE;
- ENDTRY
-
- return (ODInfoType)frameInfo;
- }
-
- //------------------------------------------------------------------------------
- // Method: WritePartInfo
- // Origin: ODPart
- //
- // Description: When a frame is being externalized by the Draft, it will ask the
- // owner (part) to write out its info annotation on the frame.
- //
- // The part uses a C++ helper class to encapsulate the information
- // we store with each frame, so we let it externalize itself to
- // the storage unit view.
- //------------------------------------------------------------------------------
-
- void SamplePart::WritePartInfo( Environment* ev,
- ODInfoType partInfo,
- ODStorageUnitView* storageUnitView )
- {
- SOM_Trace("SamplePart","WritePartInfo");
-
- // Tell our frame info class to write itself out into the pre-
- // focused storage unit.
- ((CFrameInfo*) partInfo)->Externalize(ev, storageUnitView);
- }
-
- //------------------------------------------------------------------------------
- // Method: ClonePartInfo
- // Origin: ODPart
- //
- // Description: When a frame is being cloned by the Draft, it will ask the owner
- // (part) to clone its info annotation on the frame.
- //
- // The part uses a C++ helper class to encapsulate the information
- // we store with each frame, so we let it clone itself to the
- // storage unit view.
- //------------------------------------------------------------------------------
-
- void SamplePart::ClonePartInfo( Environment* ev,
- ODDraftKey key,
- ODInfoType partInfo,
- ODStorageUnitView* storageUnitView,
- ODFrame* scopeFrame )
- {
- SOM_Trace("SamplePart","ClonePartInfo");
-
- // Tell our frame info class to write itself out into the pre-
- // focused storage unit.
- ((CFrameInfo*) partInfo)->CloneInto(ev, key, storageUnitView, scopeFrame);
- }
-
- //==============================================================================
- #pragma mark • Layout •
- //==============================================================================
-
- //------------------------------------------------------------------------------
- // Method: DisplayFrameAdded
- // Origin: ODPart
- //
- // Description: This method is called in response to a frame being created for
- // the part.
- //
- // The part records the existence of a new display frame in its
- // internal display frame list, as well as, verifies that the frame
- // is "set up" correctly (ie. valid viewType). The part also
- // creates and stores its "frame info" class in the new frame.
- //------------------------------------------------------------------------------
-
- void SamplePart::DisplayFrameAdded( Environment* ev,
- ODFrame* frame )
- {
- SOM_Trace("SamplePart","DisplayFrameAdded");
-
- // If we are being embedded in another part, the presentation field
- // will (most likely) be unset; we need to set it something meaningful.
- // The view field may also be unset, if so, we prefer to be displayed
- // in a frame view.
-
- if ( frame->GetPresentation(ev) != gGlobals->fMainPresentation )
- frame->SetPresentation(ev, gGlobals->fMainPresentation);
-
- if ( frame->GetViewType(ev) == kODNullTypeToken )
- frame->SetViewType(ev, gGlobals->fFrameView);
-
- // Hang our "state" info off of the new display frame. We use
- // the CFrameInfo object for activation, updating, and window
- // maintenance.
- CFrameInfo* frameInfo = new CFrameInfo(ODGetSession(ev,fSelf));
- frame->SetPartInfo(ev, (ODInfoType)frameInfo);
-
- // If the frame being added is a root frame, we know that a window
- // is associated with this frame. Notify ourselves that we need to
- // clean it up when the frame goes away.
- if ( frame->IsRoot(ev) )
- frameInfo->SetShouldDisposeWindow(kODTrue);
-
- // The proxy class will refcount the frame passed to it, so we
- // don't need to worry about refcounting the display frame.
- CFrameProxy* proxy = new CFrameProxy;
- proxy->InitFrameProxy(ev,frame);
-
- // Add the proxy to the display frame collection.
- fDisplayFrames->Add(proxy);
-
- // Since we maintain a persistent list of weak references to our
- // display frames, having one added to the part dirties it, but
- // only if the frame is "persistent".
- if ( frame->GetStorageUnit(ev) )
- this->SetDirty(ev);
- }
-
- //------------------------------------------------------------------------------
- // Method: DisplayFrameConnected
- // Origin: ODPart
- //
- // Description: This method is called when one of our display frames, previously
- // written out, is internalized. This method is called instead of
- // DisplayFrameAdded because a "new" frame is not being created;
- // an existing one is being reconstituted.
- //
- // The part first checks to see if we can match its frame to an
- // ID in the Display frame list; if so, we put the frame into the
- // proxy. For frames we do not recognize, just add them.
- //
- // Warning: This method may be calle,d during editor swapping, with a frame
- // not recognized by the part. This is ok. Just treat the case as
- // if a "new" frame were being added to the part.
- //------------------------------------------------------------------------------
-
- void SamplePart::DisplayFrameConnected( Environment* ev,
- ODFrame* frame )
- {
- SOM_Trace("SamplePart","DisplayFrameConnected");
-
- // Iterate over our display collection to match the frame with
- // an existing proxy with the correct frame ID. If we find it,
- // replace the ID with the actual frame. If we don't find it,
- // treat it as a newly "added" frame.
- ODBoolean found = kODFalse;
- CListIterator fiter(fDisplayFrames);
- for ( CFrameProxy* proxy = (CFrameProxy*) fiter.First();
- fiter.IsNotComplete(); proxy = (CFrameProxy*) fiter.Next() )
- {
- if ( proxy->GetID() == frame->GetID(ev) )
- {
- // The proxy class will refcount the frame passed to it, so we
- // don't need to worry about refcounting the display frame.
- proxy->SetFrame(ev,frame);
- found = kODTrue;
- }
- }
-
- // Parts typically operate under the assumption that they have previous
- // knowledge of a frame before it is connected to it. This knowledge
- // should come from having read in the frame reference when the part
- // was internalized. If the frame is an "unknown", the part was probably
- // bound to another editors storage unit because the editor is missing or
- // the user changed the editor in the Info dialog.
- if ( found )
- {
- // If a display frame is connected to us with an unrecognizable
- // presentation, we need to set it to something meaningful.
-
- if ( frame->GetPresentation(ev) != gGlobals->fMainPresentation )
- frame->SetPresentation(ev, gGlobals->fMainPresentation);
-
- if ( frame->IsRoot(ev) )
- {
- // If the frame being added is a root frame, we know that a window
- // is associated with this frame. Notify ourselves that we need to
- // clean it up when the frame goes away.
- CFrameInfo* frameInfo = (CFrameInfo*) frame->GetPartInfo(ev);
- frameInfo->SetShouldDisposeWindow(kODTrue);
-
- // In addition, we need to verify that the frame is in "frame" view.
- // If the user dragged an icon from a document to Finder and then
- // opens the resultant document, the view would be "icon". However
- // displaying a icon is useless, so we need to change the view to
- // frame.
- if ( frame->GetViewType(ev) != gGlobals->fFrameView )
- frame->SetViewType(ev, gGlobals->fFrameView);
- }
- }
- else
- {
- // If an unrecognizable frame is connected to us, treat it like a "new"
- // frame and call our method to add it.
- this->DisplayFrameAdded(ev, frame);
- }
- }
-
- //------------------------------------------------------------------------------
- // Method: DisplayFrameRemoved
- // Origin: ODPart
- //
- // Description: This method is called in response to a frame being removed from
- // the part.
- //
- // The part removes the frame from its internal display frame list
- // and reliquishes any foci that it still owned. Lastly, if the
- // frame has a source frame (it was the root frame of a part
- // window), we will record the part window bounds so that any
- // subsequent part windows opened on the source frame will appear
- // in the same location.
- //------------------------------------------------------------------------------
-
- void SamplePart::DisplayFrameRemoved( Environment* ev,
- ODFrame* frame )
- {
- SOM_Trace("SamplePart","DisplayFrameRemoved");
-
- TRY
- CFrameInfo* frameInfo = (CFrameInfo*) frame->GetPartInfo(ev);
-
- // Make sure the frame going away does not own any foci. Forgetting
- // to do this, will cause a "refcounting" error when the frame
- // is deleted by the draft.
- this->RelinquishAllFoci(ev, frame);
-
- // If removing a child window, show zoom rects back to source.
- // NOTE: This has to be done before CleanupDisplayFrame because
- // CleanupDisplayFrame will remove the relationship.
- if ( frame->IsRoot(ev) && frameInfo->HasSourceFrame() )
- {
- TempODWindow window = frame->AcquireWindow(ev);
- this->ZoomPartWindow(ev, frameInfo->GetSourceFrame(ev),
- window, kWindowClosing);
- }
-
- // Clean up the display frame.
- this->CleanupDisplayFrame(ev, frame, kFrameRemoved);
- // Clean up any associated window.
- this->CleanupWindow(ev, frame);
- // Dispose of the frame's runtime state info.
- frame->SetPartInfo(ev, (ODInfoType) kODNULL);
- ODDeleteObject(frameInfo);
-
- // Remove the display frame from our collection.
- CListIterator fiter(fDisplayFrames);
- for ( CFrameProxy* proxy = (CFrameProxy*) fiter.First();
- fiter.IsNotComplete(); proxy = (CFrameProxy*) fiter.Next() )
- {
- if ( ODObjectsAreEqual(ev, proxy->GetFrame(ev), frame) )
- {
- // Delete the proxy object and its contents. The frame's
- // refcount will be decremented in the proxy destructor.
- fiter.RemoveCurrent();
- delete proxy;
- }
- }
-
- // Since we maintain a persistent list of weak references to our
- // display frames, having one removed from the part dirties it, but
- // only if the frame is persistent.
- if ( frame->GetStorageUnit(ev) )
- this->SetDirty(ev);
-
- CATCH_ALL
- // Alert the user of the problem.
- this->DoDialogBox(ev, frame, kErrorBoxID, kErrRemoveFrame);
- // Change the exception value, so the DocShell doesn't display an
- // error dialog.
- SetErrorCode(kODErrAlreadyNotified);
- // Alert the caller.
- RERAISE;
- ENDTRY
- }
-
- //------------------------------------------------------------------------------
- // Method: DisplayFrameClosed
- // Origin: ODPart
- //
- // Description: This method is called in response to a frame being closed as a
- // result of the document having been closed by the user.
- //
- // The part behaves much the same way that it would if a frame were
- // removed (see above), except that we don't need to cache runtime
- // information.
- //------------------------------------------------------------------------------
-
- void SamplePart::DisplayFrameClosed( Environment* ev,
- ODFrame* frame )
- {
- SOM_Trace("SamplePart","DisplayFrameClosed");
-
- TRY
- CFrameInfo* frameInfo = (CFrameInfo*) frame->GetPartInfo(ev);
-
- // Make sure the frame going away does not own any foci. Forgetting
- // to do this, will cause a "refcounting" error when the frame
- // is deleted by the draft.
- this->RelinquishAllFoci(ev, frame);
-
- // Clean up the display frame.
- this->CleanupDisplayFrame(ev, frame, kFrameClosed);
- // Clean up any associated window.
- this->CleanupWindow(ev, frame);
- // Dispose of the frame's runtime state info.
- frame->SetPartInfo(ev, (ODInfoType) kODNULL);
- ODDeleteObject(frameInfo);
-
- // Remove the display frame from our collection.
- CListIterator fiter(fDisplayFrames);
- for ( CFrameProxy* proxy = (CFrameProxy*) fiter.First();
- fiter.IsNotComplete(); proxy = (CFrameProxy*) fiter.Next() )
- {
- if ( proxy->GetID() == frame->GetID(ev) )
- {
- // Release the frame reference, but don't get rid of the
- // proxy object because "closed" frames may be reconnected
- // before the document is really closed.
- proxy->Purge(ev);
- }
- }
-
- CATCH_ALL
- // Alert the user of the problem.
- this->DoDialogBox(ev, frame, kErrorBoxID, kErrRemoveFrame);
- // Change the exception value, so the DocShell doesn't display an
- // error dialog.
- SetErrorCode(kODErrAlreadyNotified);
- // Alert the caller.
- RERAISE;
- ENDTRY
- }
-
- //------------------------------------------------------------------------------
- // Method: CleanupDisplayFrame
- // Origin: SamplePart
- //
- // Description: This method is called when a frame has been closed or removed.
- // The method cleans up the references and state information stored
- // in the CFrameInfo class.
- //------------------------------------------------------------------------------
-
- void SamplePart::CleanupDisplayFrame( Environment* ev,
- ODFrame* frame,
- ODBoolean frameRemoved )
- {
- SOM_Trace("SamplePart","CleanupDisplayFrame");
-
- ODError error = noErr;
- CFrameInfo* frameInfo = (CFrameInfo*) frame->GetPartInfo(ev);
-
- TRY
- // If we are the root of a child window, we need to notify
- // our source frame that we are going away.
- if ( frameInfo->HasSourceFrame() )
- {
- ODFrame* sourceFrame = frameInfo->GetSourceFrame(ev);
- CFrameInfo* sourceFrameInfo = (CFrameInfo*) sourceFrame->GetPartInfo(ev);
-
- if ( frameRemoved )
- {
- // Invalidate the source frame. We do this because the
- // source frame may have a unique display when it has
- // been opened into a part window. This forces the
- // frame to redraw "not opened".
- sourceFrame->Invalidate(ev, kODNULL, kODNULL);
- }
-
- // Tell the source frame that its dependent is going away.
- sourceFrameInfo->ReleaseDependentFrame(ev);
-
- // Release our reference to the source frame.
- frameInfo->ReleaseSourceFrame(ev);
-
- // If the frame is the root, it is a part window going away
- // and we need to notify our source frame that it no longer
- // has a part window.
- if ( frame->IsRoot(ev) )
- sourceFrameInfo->SetPartWindow(ev, kODNULL);
- }
- CATCH_ALL
- error = ErrorCode();
- ENDTRY
-
- TRY
- // If the frame was removed from the document, we need to remove
- // any child window displaying that frame.
- if ( frameRemoved )
- {
- // If we have a child window, we need to close it.
- ODWindow* window = frameInfo->AcquirePartWindow(ev);
-
- if ( window )
- {
- frameInfo->SetPartWindow(ev, kODNULL);
- window->CloseAndRemove(ev);
- }
- }
- CATCH_ALL
- error = ErrorCode();
- ENDTRY
-
- TRY
- // If we have dependent frames, we need to notify them that we
- // are going away.
-
- if ( frameInfo->HasDependentFrame() )
- {
- // Get the frame that is dependent on this one. We can safely
- // do this because we only reference our own display frames.
- ODFrame* dependentFrame = frameInfo->GetDependentFrame(ev);
- CFrameInfo* dependentFrameInfo = (CFrameInfo*) dependentFrame->GetPartInfo(ev);
-
- // Tell the dependent frame that its source is going away.
- dependentFrameInfo->ReleaseSourceFrame(ev);
-
- // Release our reference to the dependent frame.
- frameInfo->ReleaseDependentFrame(ev);
- }
- CATCH_ALL
- error = ErrorCode();
- ENDTRY
-
- // If anything went wrong, signal an error.
- THROW_IF_ERROR(error);
- }
-
- //------------------------------------------------------------------------------
- // Method: AttachSourceFrame
- // Origin: ODPart
- //
- // Description: If the part which we are contained in is opened into a part
- // window, it is required to iterate over its embedded frames and
- // add new display frames in the part window. After each new
- // embedded frame is created, this method will be called.
- //
- // Given all that, and given our lack of interesting
- // content, we just validate the frame and attach it to its source.
- //------------------------------------------------------------------------------
-
- void SamplePart::AttachSourceFrame( Environment* ev,
- ODFrame* frame,
- ODFrame* sourceFrame )
- {
- SOM_Trace("SamplePart","AttachSourceFrame");
-
- // Tell the new frame about its source.
- CFrameInfo* frameInfo = (CFrameInfo*) frame->GetPartInfo(ev);
- frameInfo->SetSourceFrame(ev, sourceFrame);
-
- // And tell the source about its new dependent.
- frameInfo = (CFrameInfo*) sourceFrame->GetPartInfo(ev);
- frameInfo->SetDependentFrame(ev, frame);
-
- // In both cases, refcounting of the frame and sourceFrame is
- // handled by the CFrameInfo class.
- }
-
- //------------------------------------------------------------------------------
- // Method: ViewTypeChanged
- // Origin: ODPart
- //
- // Description: This method is called in response to one of our display frame's
- // viewType field being modified. We call this method on ourselves
- // when new display frames are added, but it call also be called
- // when the user changes the view in the "part info" dialog.
- //------------------------------------------------------------------------------
-
- void SamplePart::ViewTypeChanged( Environment* ev,
- ODFrame* frame )
- {
- SOM_Trace("SamplePart","ViewTypeChanged");
-
- // Change this frame's used shape to match the new view setting.
- TempODShape newUsedShape = this->CalcNewUsedShape(ev, frame);
-
- frame->Invalidate(ev, kODNULL, kODNULL);
- frame->ChangeUsedShape(ev, newUsedShape, kODNULL);
- frame->Invalidate(ev, kODNULL, kODNULL);
- }
-
- //------------------------------------------------------------------------------
- // Method: CalcNewUsedShape
- // Origin: SamplePart
- //
- // Description: This method is called in response to one of display frame's view
- // being changed. The method calculates the appropriate usedShape
- // for the new view type.
- //------------------------------------------------------------------------------
-
- ODShape* SamplePart::CalcNewUsedShape( Environment* ev,
- ODFrame* frame )
- {
- SOM_Trace("SamplePart","CalcNewUsedShape");
-
- ODShape* usedShape = kODNULL; ODVolatile(usedShape);
- RgnHandle usedRgn; ODVolatile(usedRgn);
-
- // If the view is "frame", we intentionally return a nil shape;
- // doing so, will reset the used shape to equal the frame shape.
-
- ODTypeToken view = frame->GetViewType(ev);
-
- if ( view == gGlobals->fLargeIconView ||
- view == gGlobals->fSmallIconView ||
- view == gGlobals->fThumbnailView )
- {
- TRY
- Rect bounds;
- usedRgn = ODNewRgn();
-
- if ( view == gGlobals->fLargeIconView || view == gGlobals->fSmallIconView )
- {
- CUsingLibraryResources res;
-
- // Set the bounds rect for the icon size.
- SetRect(&bounds, 0, 0,
- (view == gGlobals->fLargeIconView) ? kODLargeIconSize : kODSmallIconSize,
- (view == gGlobals->fLargeIconView) ? kODLargeIconSize : kODSmallIconSize);
-
- // Convert the icon mask into a Region.
- THROW_IF_ERROR( IconIDToRgn(usedRgn, &bounds, atAbsoluteCenter, kBaseResourceID) );
- }
- else if ( view == gGlobals->fThumbnailView )
- {
- PicHandle thumbnail = this->GenerateThumbnail(ev, frame);
-
- if ( thumbnail )
- bounds = (**thumbnail).picFrame;
- else
- SetRect(&bounds, 0, 0, kODThumbnailSize, kODThumbnailSize);
-
- RectRgn(usedRgn,&bounds);
- }
-
- usedShape = frame->CreateShape(ev);
- usedShape->SetQDRegion(ev, usedRgn);
-
- CATCH_ALL
- ODSafeReleaseObject(usedShape);
- ODDisposeHandle((ODHandle)usedRgn);
- usedShape = kODNULL;
- ENDTRY
- }
-
- return usedShape;
- }
-
- //------------------------------------------------------------------------------
- // Method: UpdateFrame
- // Origin: SamplePart
- //
- // Description: This method is called in response to one of our
- //------------------------------------------------------------------------------
-
- void SamplePart::UpdateFrame( Environment* ev,
- ODFrame* frame,
- ODTypeToken view,
- ODShape* usedShape )
- {
- SOM_Trace("SamplePart","UpdateFrame");
-
- TRY
- // Update the frame to have the new view and UsedShape.
- frame->Invalidate(ev, kODNULL, kODNULL);
- frame->SetViewType(ev, view);
- frame->ChangeUsedShape(ev, usedShape, kODNULL);
- frame->Invalidate(ev, kODNULL, kODNULL);
- CATCH_ALL
- // Failing isn't great, but we can live with it, so don't set ev.
- ENDTRY
- }
-
- //------------------------------------------------------------------------------
- // Method: FrameShapeChanged
- // Origin: ODPart
- //
- // Description: This method is called in response to a frame's shape being
- // altered, either by the user or the part we are embedded in.
- //
- // To keep all dependent frames in sync, we need to propogate the
- // new frame shape the frames dependent on the changed frame. This
- // is done by observing the display frames stored in the frame info
- // and calling RequestFrameShape for each.
- //------------------------------------------------------------------------------
-
- void SamplePart::FrameShapeChanged( Environment* ev,
- ODFrame* frame )
- {
- SOM_Trace("SamplePart","FrameShapeChanged");
-
- // Adjust the "used" shape for the new frame shape.
- TempODShape usedShape = this->CalcNewUsedShape(ev, frame);
- frame->ChangeUsedShape(ev, usedShape, kODNULL);
- }
-
- //------------------------------------------------------------------------------
- // Method: Open
- // Origin: ODPart
- //
- // Description: This method is called when OpenDoc, a containing part, or the
- // active editor would like to open a frame into a seperate window.
- // If a source frame is passed into this method, the editor is
- // being asked one of two things. If the frame is the root, we are
- // being asked to open an existing document. If the frame is not
- // the root, we are being asked to open a part window. If a source
- // frame is not specified, the editor is being asked to open a new
- // window.
- //------------------------------------------------------------------------------
-
- ODID SamplePart::Open( Environment* ev,
- ODFrame* frame )
- {
- SOM_Trace("SamplePart","Open");
-
- ODID windowID;
- TempODWindow window(kODNULL);
-
- WindowProperties* windowProperties = kODNULL;
- ODVolatile(windowProperties);
-
- TRY
- // Because the frame parameter being passed to us can be one of
- // three things, we must determine what it is; either the root
- // frame of a existing document, the source frame for a part
- // window, or null if we are opening a new document.
-
- if ( frame == kODNULL )
- {
- // Calculate the bounding rectangle for a new window
- Rect windowRect = this->CalcPartWindowSize(ev, kODNULL);
- // Get the default setting for a document window.
- windowProperties = this->GetDefaultWindowProperties(ev, kODNULL, &windowRect);
- // Create a Mac Window and register it with OpenDoc.
- window = this->CreateWindow(ev, kODNULL, kODFrameObject, windowProperties);
- }
- else if ( frame->IsRoot(ev) )
- {
- // Get the previously saved settings for the document window.
- windowProperties = this->GetSavedWindowProperties(ev, frame);
-
- if ( windowProperties == kODNULL )
- {
- // Calculate the bounding rectangle for a new window
- Rect windowRect = this->CalcPartWindowSize(ev, frame);
- // Get the default setting for a document window.
- windowProperties = this->GetDefaultWindowProperties(ev, kODNULL, &windowRect);
- }
-
- // Create a Mac Window and register it with OpenDoc.
- window = this->CreateWindow(ev, frame, kODFrameObject, windowProperties);
-
- // We release the source frame here because we didn't call
- // EndGetWindowProperties and becuase we are done with it.
- ODReleaseObject(ev, windowProperties->sourceFrame);
- }
- else // frame is a source frame
- {
- window = this->AcquireFramesWindow(ev, frame);
-
- if ( window == kODNULL )
- {
- // Calculate the bounding rectangle for a new window
- Rect windowRect = this->CalcPartWindowSize(ev, frame);
- // Get the default setting for a document window.
- windowProperties = this->GetDefaultWindowProperties(ev, frame, &windowRect);
- // Create a Mac Window and register it with OpenDoc.
- window = this->CreateWindow(ev, kODNULL, kODFrameObject, windowProperties);
-
- // Tell the source frame that it is opened in a part window.
- CFrameInfo* frameInfo = (CFrameInfo*) frame->GetPartInfo(ev);
- frameInfo->SetPartWindow(ev, window);
-
- this->ZoomPartWindow(ev, frame, window, kWindowOpening);
- }
- }
-
- // Create the window's root facet.
- window->Open(ev);
- // Make the window visible.
- window->Show(ev);
- // Activate and select the window.
- window->Select(ev);
-
- // Cleanup allocate memory.
- ODDeleteObject(windowProperties);
-
- // Get window id to return.
- windowID = (window ? window->GetID(ev) : kODNULLID);
-
- CATCH_ALL
- // If we threw early, the source frame's refcount may be too high.
- if ( windowProperties )
- ODSafeReleaseObject(windowProperties->sourceFrame);
- // Cleanup the created items.
- ODDeleteObject(windowProperties);
- windowID = kODNULLID;
- // Alert the caller.
- RERAISE;
- ENDTRY
-
- return windowID;
- }
-
- //------------------------------------------------------------------------------
- // Method: AcquireFramesWindow
- // Origin: SamplePart
- //
- // Description: This method is called by the part when a frame, that has been
- // previously opened, is being opened again.
- //
- // The method retrieves the existing window for the frame and
- // returns it.
- //------------------------------------------------------------------------------
-
- ODWindow* SamplePart::AcquireFramesWindow( Environment* ev,
- ODFrame* frame )
- {
- SOM_Trace("SamplePart","GetFramesWindow");
-
- CFrameInfo* frameInfo = (CFrameInfo*) frame->GetPartInfo(ev);
- ODWindow* window = frameInfo->AcquirePartWindow(ev);
-
- return window;
- }
-
- //------------------------------------------------------------------------------
- // Method: CreateWindow
- // Origin: SamplePart
- //
- // Description: This method is called by the part when a window needs to be
- // created for a frame being opened.
- //
- // The part uses the information passed in windowProperties to
- // create the appropriate window. The generated window is
- // registered with OpenDoc as a new window (RegisterWindow) or as a
- // window from an existing document (RegisterWindowForFrame).
- //------------------------------------------------------------------------------
-
- ODWindow* SamplePart::CreateWindow( Environment* ev,
- ODFrame* frame,
- ODType frameType,
- WindowProperties* windowProperties)
- {
- SOM_Trace("SamplePart","CreateWindow");
-
- ODPlatformWindow platformWindow = kODNULL;
- ODWindow* window = kODNULL;
-
- // Using the name and the calculated rectangle, create a new window.
- // Note that we are allocating the window record in temp mem using
- // the OpenDoc memory mgr. This helps reduce app heap usage.
- // In addition, OpenDoc requires that all new windows be initially hidden
- // so that it can correctly layer windows/palettes.
- platformWindow = NewCWindow((Ptr)ODNewPtr(sizeof(WindowRecord)),
- &(windowProperties->boundsRect),
- windowProperties->title,
- kODFalse, /* visible */
- windowProperties->procID,
- (WindowPtr)-1L,
- windowProperties->hasCloseBox,
- windowProperties->refCon);
-
- if ( platformWindow )
- {
- TRY
- ODWindowState* windowState = ODGetSession(ev,fSelf)->GetWindowState(ev);
-
- // Shoud the window be saved in the document? Yes if the root frame is
- // persistent.
- ODBoolean saveWindow = (ODISOStrCompare(frameType,kODFrameObject) == 0);
-
- // Tell the window object that we will be disposing the window record
- // when the root frame is closed/removed.
- ODBoolean shouldDispose = kODFalse;
-
- // Determine whether we are creating a new window (frame is null),
- // or opening a previous saved window (frame is valid).
-
- if ( frame == kODNULL )
- {
- // Tell OpenDoc about it by creating an OpenDoc window object.
- window = windowState->
- RegisterWindow(ev,
- platformWindow, // Macintosh WindowPtr
- frameType, // Frame type (Persistent/Non-persistent)
- windowProperties->isRootWindow, // Is this a document window?
- windowProperties->isResizable, // Is this window resizeable?
- windowProperties->isFloating, // Is this window floating?
- saveWindow, // Should this window be persistent?
- shouldDispose, // (see comment above)
- fSelf, // Part reference to us
- gGlobals->fFrameView, // What view should the window have?
- gGlobals->fMainPresentation, // What presentation should the window have?
- windowProperties->sourceFrame); // The display frame being opened, if any
- }
- else
- {
- // Tell OpenDoc about it by creating an OpenDoc window object.
- window = windowState->
- RegisterWindowForFrame(ev,
- platformWindow, // Macintosh WindowPtr
- frame, // Frame type (Persistent/Non-persistent)
- windowProperties->isRootWindow, // Is this a document window?
- windowProperties->isResizable, // Is this window resizeable?
- windowProperties->isFloating, // Is this window floating?
- saveWindow, // Should this window be persistent?
- shouldDispose, // (see comment above)
- windowProperties->sourceFrame); // The display frame being opened, if any
- }
-
- CATCH_ALL
- // Cleanup Macintosh Window.
- CloseWindow(platformWindow);
- ODDisposePtr(platformWindow);
- // Get the right error message for the problem.
- ODSShort errMsgNum = (!frame && windowProperties->sourceFrame)
- ? kErrCantOpenPartWindow : kErrCantOpenDocWindow;
- // Alert the user of the problem.
- this->DoDialogBox(ev, frame, kErrorBoxID, errMsgNum);
- // Change the exception value, so the DocShell doesn't display an
- // error dialog.
- SetErrorCode(kODErrAlreadyNotified);
- // Alert the caller.
- RERAISE;
- ENDTRY
- }
-
- return window;
- }
-
- //------------------------------------------------------------------------------
- // Method: CleanupWindow
- // Origin: SamplePart
- //
- // Description: This method is called by the part when a window needs to be
- // cleaned up for a frame being closed/removed.
- //
- // The part deallocates the window buffer allocated in the
- // CreateWindow() method.
- //------------------------------------------------------------------------------
-
- void SamplePart::CleanupWindow( Environment* ev,
- ODFrame* frame )
- {
- SOM_Trace("SamplePart","CleanupWindow");
-
- TRY
- CFrameInfo* frameInfo = (CFrameInfo*) frame->GetPartInfo(ev);
- if ( frameInfo->ShouldDisposeWindow() )
- {
- TempODWindow window = frame->AcquireWindow(ev);
- THROW_IF_NULL(window);
-
- ODPlatformWindow windowPtr = window->GetPlatformWindow(ev);
- CloseWindow(windowPtr);
- ODDisposePtr(windowPtr);
- }
- CATCH_ALL
- this->DoDialogBox(ev, frame, kErrorBoxID, kErrWindowGone);
- // consume excpetion because it's not fatal.
- ENDTRY
- }
-
- //------------------------------------------------------------------------------
- // Method: GetDefaultWindowProperties
- // Origin: SamplePart
- //
- // Description: This method is called by the part when a new window is being
- // created. The method examines the frame which is being opened
- // a generates the default window parameters to pass to the
- // Mac Toolbox.
- //------------------------------------------------------------------------------
-
- WindowProperties*
- SamplePart::GetDefaultWindowProperties( Environment* ev,
- ODFrame* sourceFrame,
- Rect* windowRect )
- {
- SOM_Trace("SamplePart","GetDefaultWindowProperties");
-
- WindowProperties* windowProperties = new WindowProperties;
-
- TRY
- // Calculate the offset for the window based on the sourceFrame.
- if ( sourceFrame )
- this->CalcPartWindowPosition(ev, sourceFrame, windowRect);
- else
- OffsetRect(windowRect, kALittleNudge,
- GetMBarHeight() + kMacWindowTitleBarHeight);
-
- // Set the window bounds based on the calculated rect.
- windowProperties->boundsRect = *windowRect;
-
- // Get the part's name to use for the new window.
- TempODIText windowName = GetPartName(ev, fSelf, kSamplePartCategory);
- // Convert the ODIText into a Pascal string.
- GetITextString(windowName, windowProperties->title);
-
- // Fill in the other fields of the Window Properties struct.
-
- windowProperties->procID = zoomDocProc;
- windowProperties->hasCloseBox = kODTrue;
- windowProperties->refCon = (long) kODNULL;
- windowProperties->wasVisible = kODFalse;
- windowProperties->isResizable = kODTrue;
- windowProperties->isFloating = kODFalse;
- windowProperties->isRootWindow = sourceFrame ? kODFalse : kODTrue;
- windowProperties->shouldShowLinks = kODFalse;
- windowProperties->sourceFrame = sourceFrame;
- CATCH_ALL
- // Clean up and...
- ODDeleteObject(windowProperties);
- // Alert the caller.
- RERAISE;
- ENDTRY
-
- return windowProperties;
- }
-
- //------------------------------------------------------------------------------
- // Method: GetSavedWindowProperties
- // Origin: SamplePart
- //
- // Description: This method is called by the part to read in saved information
- // for a window from an existing document.
- //------------------------------------------------------------------------------
-
- WindowProperties* SamplePart::GetSavedWindowProperties( Environment* ev,
- ODFrame* frame )
- {
- SOM_Trace("SamplePart","GetSavedWindowProperties");
-
- WindowProperties* windowProperties = new WindowProperties;
-
- // If we fail to load the window properties from storage, delete
- // the structure so the calling code will behave appropriately.
- if ( BeginGetWindowProperties(ev, frame, windowProperties) )
- {
- // Note: We don't call EndGetWindowProperties because it releases the
- // source frame, which we will need after this method returns.
-
- // Get the part's name to use for the new window.
- TempODIText windowName = GetPartName(ev, fSelf, kSamplePartCategory);
- // Convert the ODIText into a Pascal string.
- GetITextString(windowName, windowProperties->title);
-
- // Verify the window is still visible on a monitor.
-
- RgnHandle windowRgn = ODNewRgn();
- ODBoolean repositionWindow = kODFalse;
-
- // We are only concerned with the window's title bar being
- // visible, so calcuate the titlebar rect from the current
- // window bounds.
- Rect adjustedBounds = windowProperties->boundsRect;
- adjustedBounds.bottom = adjustedBounds.top;
- adjustedBounds.top -= kMacWindowTitleBarHeight;
-
- // Intersect the monitor's region
- RectRgn(windowRgn, &adjustedBounds);
- SectRgn(windowRgn, GetGrayRgn(), windowRgn);
-
- if ( !EmptyRgn(windowRgn) )
- {
- // If the visible portion of the window is too small, we need
- // to reposition it.
- Rect intersectedBounds = (**windowRgn).rgnBBox;
- if ( (intersectedBounds.right-intersectedBounds.left < kMinHorzVisPortion) ||
- (intersectedBounds.bottom-intersectedBounds.top < kMinVertVisPortion) )
- repositionWindow = kODTrue;
- }
- else
- {
- // If the window is completely offscreen, we need to reposition it.
- repositionWindow = kODTrue;
- }
- ODDisposeHandle((ODHandle)windowRgn);
-
- // If not, we need to move it so the user can see it.
- if ( repositionWindow )
- {
- Rect windowRect = (windowProperties->boundsRect);
- // Move the window to {0,0} coordinates.
- OffsetRect(&windowRect, -windowRect.left, -windowRect.top);
- // Now move the window to the default window position.
- OffsetRect(&windowRect, kALittleNudge, GetMBarHeight() + kMacWindowTitleBarHeight);
- // Save the new window position in our windowProperties.
- windowProperties->boundsRect = windowRect;
- }
- }
- else
- {
- // If we were unable to re-load window properties, dispose of the
- // struct.
- ODDeleteObject(windowProperties);
- }
-
- return windowProperties;
- }
-
- //------------------------------------------------------------------------------
- // Method: CalcPartWindowSize
- // Origin: SamplePart
- //
- // Description: This method is called by the part to determine what size a new
- // window shoud be.
- //------------------------------------------------------------------------------
-
- Rect SamplePart::CalcPartWindowSize( Environment* ev,
- ODFrame* sourceFrame )
- {
- SOM_Trace("SamplePart","CalcPartWindowSize");
-
- const ODSShort kOnePageWidth = 600;
-
- Rect windowRect;
- ODRect frameRect;
-
- // If a source frame is given, the part is being asked to open one of
- // its display frames into a part window. Otherwise, we are being opened
- // as the root frame of the current document and should size the window
- // accordingly.
-
- // Set up the child window's size to be that of the display frame being opened.
- if ( sourceFrame )
- {
- // Retrieve the fixed point bounding box for the frame.
- TempODShape frameShape = sourceFrame->AcquireFrameShape(ev, kODNULL);
- frameShape->GetBoundingBox(ev, &frameRect);
-
- // Convert that into a Quickdraw rectangle.
- FixedToIntRect(frameRect, windowRect);
- }
- // Otherwise, just open a large window.
- else
- {
- // (3 * kODLargeIconSize) prevents the window from covering the volume
- // icons on the desktop which is a violation of Macintosh HI Guidelines.
-
- SetRect(&windowRect, 0, 0,
- ODQDGlobals.screenBits.bounds.right - (3 * kODLargeIconSize),
- ODQDGlobals.screenBits.bounds.bottom
- - GetMBarHeight() - kMacWindowTitleBarHeight - kALittleNudge);
-
- if ( windowRect.right - windowRect.left > kOnePageWidth )
- windowRect.right = windowRect.left + kOnePageWidth;
- }
-
- return windowRect;
- }
-
- //------------------------------------------------------------------------------
- // Method: CalcPartWindowPosition
- // Origin: SamplePart
- //
- // Description: This method is called by the part to determine where to align
- // the new window (top left corner of the screen or tiled to a
- // frame).
- //------------------------------------------------------------------------------
-
- Rect SamplePart::CalcPartWindowPosition( Environment* ev,
- ODFrame* frame,
- Rect* partWindowBounds )
- {
- SOM_Trace("SamplePart","CalcPartWindowPosition");
-
- ODFacet* activeFacet;
- ODShape* frameShape;
- ODRect bbox;
- Rect bounds;
-
- // We need to know which facet of the frame we are opening to position
- // the child window.
- activeFacet = this->GetActiveFacetForFrame(ev, frame);
-
- // This should never occur, but if it did, it would be fatal.
- // So we will just pass back the same rectangle.
- if ( activeFacet == kODNULL )
- return *partWindowBounds;
-
- // For the purposes of tiling, we need the to know the area of the
- // document the frame occupies. We do this by getting the bouding
- // box and offsetting it by the aggregate external window transform
- // of the facet.
-
- frameShape = activeFacet->GetFrame(ev)->AcquireFrameShape(ev, kODNULL);
- TempODTransform windowFrameTransform = activeFacet->AcquireWindowFrameTransform(ev, kODNULL);
- TempODShape boundsShape = ODCopyAndRelease(ev, frameShape);
-
- // Translate the bounds rect into window coordinates.
- boundsShape->Transform(ev, windowFrameTransform);
-
- // Get and convert the bounding box into a QuickDraw rectangle.
- boundsShape->GetBoundingBox(ev, &bbox);
- FixedToIntRect(bbox, bounds);
-
- // We then call our method to tile the child window.
- *partWindowBounds = TilePartWindow(ev, &bounds, partWindowBounds);
-
- // Set the port and origin so we can convert the rect to
- // global Window Mgr coordinates.
- SetPort(activeFacet->GetCanvas(ev)->GetQDPort(ev));
- SetOrigin(0,-kMacWindowTitleBarHeight);
-
- // Convert the local coordinates to global Window Mgr coordinates.
- LocalToGlobal((Point*)(&(partWindowBounds->top)));
- LocalToGlobal((Point*)(&(partWindowBounds->bottom)));
-
- return *partWindowBounds;
- }
-
- //------------------------------------------------------------------------------
- // Method: ZoomPartWindow
- // Origin: SamplePart
- //
- // Description: This method is called by the part when a frame is being opened
- // or closed in the case that zooming rectangles should be shown.
- //------------------------------------------------------------------------------
-
- void SamplePart::ZoomPartWindow( Environment* ev,
- ODFrame* frame,
- ODWindow* window,
- ODBoolean openingWindow )
- {
- SOM_Trace("SamplePart","ZoomPartWindow");
-
- const ODSShort kNumZoomSteps = 12;
-
- Rect frameRect;
- {
- // We need to know which facet of the frame we are opening to position
- // the child window.
- ODFacet* zoomFacet = kODNULL;
-
- TRY
- zoomFacet = this->GetActiveFacetForFrame(ev, frame);
- CATCH_ALL
- ENDTRY
-
- // In case there isn't an active facet for the frame, .
- if ( zoomFacet == kODNULL )
- {
- TempODFrameFacetIterator iter(ev, frame);
- zoomFacet = iter.First();
- }
-
- if ( zoomFacet != kODNULL )
- {
- // For doing the zoom rects, we need the to know the area of the
- // document the frame occupies. We do this by getting the bouding
- // box and offsetting it by the aggregate external window transform
- // of the facet.
- TempODTransform windowFrameTransform =
- zoomFacet->AcquireWindowFrameTransform(ev, kODNULL);
- TempODShape boundsShape =
- ODCopyAndRelease(ev, zoomFacet->GetFrame(ev)
- ->AcquireFrameShape(ev, kODNULL));
-
- // Translate the bounds rect into window coordinates.
- boundsShape->Transform(ev, windowFrameTransform);
-
- // Get and convert the bounding box into a QuickDraw rectangle.
- ODRect bbox;
- boundsShape->GetBoundingBox(ev, &bbox);
- FixedToIntRect(bbox, frameRect);
-
- // Set the port and origin so we can convert the rect to
- // global Window Mgr coordinates.
- SetPort(zoomFacet->GetCanvas(ev)->GetQDPort(ev));
- SetOrigin(0, 0);
-
- // Convert the local coordinates to global Window Mgr coordinates.
- LocalToGlobal((Point*) &frameRect.top);
- LocalToGlobal((Point*) &frameRect.bottom);
- }
- }
-
- Rect windowRect;
- {
- ODPlatformWindow platformWindow = window->GetPlatformWindow(ev);
-
- windowRect = platformWindow->portRect;
- windowRect.top -= kMacWindowTitleBarHeight;
-
- // Set the port and origin so we can convert the rect to
- // global Window Mgr coordinates.
- SetPort(platformWindow);
- SetOrigin(0, 0);
-
- // Convert the local coordinates to global Window Mgr coordinates.
- LocalToGlobal((Point*) &windowRect.top);
- LocalToGlobal((Point*) &windowRect.bottom);
- }
-
- Rect fromRect = openingWindow ? frameRect : windowRect;
- Rect toRect = openingWindow ? windowRect : frameRect;
-
- if ( !openingWindow )
- window->Hide(ev);
-
- ZoomRects(&fromRect, &toRect, kNumZoomSteps,
- openingWindow ? zoomAccelerate : zoomDecelerate);
- }
-
- //------------------------------------------------------------------------------
- // Method: GetActiveFacetForFrame
- // Origin: SamplePart
- //
- // Description: This method is called by the part when it needs to know what the
- // current active facet is.
- //
- // The part uses this method specifically to find the facet of a
- // source frame when opening a part window.
- //------------------------------------------------------------------------------
-
- ODFacet* SamplePart::GetActiveFacetForFrame( Environment* ev,
- ODFrame* frame )
- {
- SOM_Trace("SamplePart","GetActiveFacetForFrame");
-
- ODFacet* facet = kODNULL;
- CFrameInfo* frameInfo = (CFrameInfo*) frame->GetPartInfo(ev);
-
- // If the frame is active, and it should be, get the active facet
- // from the frame state info.
- if ( frameInfo->IsFrameActive() )
- {
- facet = frameInfo->GetActiveFacet();
- }
- else
- // Otherwise, iterate over the display frames looking for one
- // that has an active facet... there should be at least one.
- {
- TempODFrameFacetIterator fiter(ev, frame);
- for ( ODFacet* selectedFacet = fiter.First(); fiter.IsNotComplete();
- selectedFacet = fiter.Next() )
- {
- if ( selectedFacet->IsSelected(ev) )
- {
- facet = selectedFacet;
- break;
- }
- }
- }
-
- // If there are no active facets anywhere, this method should never
- // have been called, so signal an error.
- if ( facet == kODNULL )
- THROW(kODErrInvalidFrame);
-
- return facet;
- }
-
- //==============================================================================
- #pragma mark • Imaging •
- //==============================================================================
-
- //------------------------------------------------------------------------------
- // Method: FacetAdded
- // Origin: ODPart
- //
- // Description: This method is called when any part adds a facet to
- // one of our display frames.
- //------------------------------------------------------------------------------
-
- void SamplePart::FacetAdded( Environment* ev,
- ODFacet* facet )
- {
- SOM_Trace("SamplePart","FacetAdded");
-
- ODFrame* frame = facet->GetFrame(ev);
- CFrameInfo* frameInfo = (CFrameInfo*) frame->GetPartInfo(ev);
-
- // If a root facet is being added, the frame should be activated when the
- // window is "selected". This prevents OpenDoc from getting into an
- // ambiguous state of no part having the selection focus.
-
- if ( frame->IsRoot(ev) )
- {
- frameInfo->SetActiveFacet(facet);
- frameInfo->SetFrameReactivate(kODTrue);
- }
-
- // If a frame had all of its facets removed, the frame would have
- // hidden any of its part windows. If the frame becomes visible again,
- // by having a facet added to it, we will "show" the part window for
- // the frame.
-
- if ( (CountFramesFacets(ev, frame) == 1) )
- {
- TempODWindow window = frameInfo->AcquirePartWindow(ev);
- if ( window ) window->Show(ev);
- }
- }
-
- //------------------------------------------------------------------------------
- // Method: FacetRemoved
- // Origin: ODPart
- //
- // Description: This method is called when any part removes a facet
- // from one of our display frames.
- //
- // The part just removes the "active" note from the
- // appropriate display frame if necessary since this
- // facet will not be available, nor active, again.
- //------------------------------------------------------------------------------
-
- void SamplePart::FacetRemoved( Environment* ev,
- ODFacet* facet )
- {
- SOM_Trace("SamplePart","FacetRemoved");
-
- ODFrame* frame = facet->GetFrame(ev);
- TempODFrame containingFrame = frame->AcquireContainingFrame(ev);
- CFrameInfo* frameInfo = (CFrameInfo*) frame->GetPartInfo(ev);
-
- // If the facet was the active facet, it can no longer be.
- if ( ODObjectsAreEqual(ev, frameInfo->GetActiveFacet(), facet) )
- frameInfo->SetActiveFacet(kODNULL);
-
- // If a frame has all of its facets removed and its containing frame set
- // to NULL, the frame becomes "hidden". If the frame owns a part window,
- // the part window should also be hidden.
-
- if ( (CountFramesFacets(ev, frame) == 0) &&
- (containingFrame == kODNULL) )
- {
- TempODWindow window = frameInfo->AcquirePartWindow(ev);
- if ( window ) window->Hide(ev);
- }
- }
-
- //------------------------------------------------------------------------------
- // Method: Draw
- // Origin: ODPart
- //
- // Description: This method is called when a facet of a part's display
- // frame intersects the invalidated portion of an OpenDoc
- // window. The invalidShape parameter passed in is the
- // portion of the facet which has been invalidated.
- //
- // The part sets up the drawing environment using a
- // C++ helper class (CFocus) and then calls the
- // appropriate drawing method based on the frame's
- // viewType.
- //------------------------------------------------------------------------------
-
- void SamplePart::Draw( Environment* ev,
- ODFacet* facet,
- ODShape* invalidShape )
- {
- SOM_Trace("SamplePart","Draw");
-
- // Focus the port and origin for drawing in our facet.
- // Note that this instance of the CFocusDrawingEnv class
- // is being allocated on the stack. When the execution
- // leaves the scope of this method, the destructor (which
- // cleans up the drawing environment) is automatically
- // called.
- CFocus initiateDrawing(ev, facet, invalidShape);
-
- ODTypeToken view = facet->GetFrame(ev)->GetViewType(ev);
-
- if ( view == gGlobals->fLargeIconView || view == gGlobals->fSmallIconView )
- this->DrawIconView(ev, facet);
- else if ( view == gGlobals->fThumbnailView )
- this->DrawThumbnailView(ev, facet);
- else
- this->DrawFrameView(ev, facet);
- }
-
- //------------------------------------------------------------------------------
- // Method: DrawFrameView
- // Origin: SamplePart
- //
- // Description: This method is called by the part when the frame being drawn is
- // in "frame" view.
- //
- // SamplePart really has not intrisic content. However, to provide
- // some visual display, we draw the class name at 80% of the
- // frame's current height using an bold font.
- //------------------------------------------------------------------------------
-
- void SamplePart::DrawFrameView( Environment* ev,
- ODFacet* facet )
- {
- SOM_Trace("SamplePart","DrawFrameView");
-
- /*ForTSMTE
- ODFrame* frame;
- ODUShort frameHeight = 0;
- ODUShort frameWidth = 0;
- RgnHandle frameRgn;
- FontInfo finfo;
- Str63 defaultString;
- CFrameInfo* frameInfo;
- GrafPtr port;
-
- GetPort(&port);
-
- // If the facet being draw is dependent to a source frame in
- // another window, we need to access the source frame to determine
- // what size to draw the content.
-
- frameInfo = (CFrameInfo*) facet->GetFrame(ev)->GetPartInfo(ev);
- if ( frameInfo->HasSourceFrame() )
- frame = frameInfo->GetSourceFrame(ev);
- else
- frame = facet->GetFrame(ev);
-
- // Get the facet's canvas so shapes are returned in the correct
- // coordinate system.
- ODCanvas* biasCanvas = facet->GetCanvas(ev);
-
- // Calculate font height for drawing.
- TempODShape frameShape = frame->AcquireFrameShape(ev, biasCanvas);
- frameRgn = frameShape->GetQDRegion(ev);
- frameHeight = (**frameRgn).rgnBBox.bottom - (**frameRgn).rgnBBox.top;
- frameWidth = (**frameRgn).rgnBBox.right - (**frameRgn).rgnBBox.left;
-
- // Save off port chararcteristics so we can restore it later.
- ODUShort size = port->txSize;
- ODUShort font = port->txFont;
- Style face = port->txFace;
-
- // Set the font size to almost fill the frame.
- TextSize((ODUShort)(frameHeight * 0.8));
- // Use the default Application font for this script system.
- TextFont(1);
- TextFace(bold + condense);
-
- GetFontInfo(&finfo);
-
- ODSLong rfRef;
- rfRef = BeginUsingLibraryResources();
- {
- PenState penState;
- GetPenState(&penState);
- PenNormal();
-
- RGBColor foreState, backState;
- GetForeColor(&foreState);
- GetBackColor(&backState);
- ForeColor(blackColor);
- BackColor(whiteColor);
-
- EraseRect(&port->portRect);
-
- GetIndString(defaultString, kMenuStringResID, kDefaultContent1ID);
- MoveTo((frameWidth / 2) - (StringWidth(defaultString) / 2),
- frameHeight - (finfo.descent - 2));
- DrawString(defaultString);
-
- // If the part is selected, fill the background with
- // the highlight color.
- if ( facet->GetHighlight(ev) == kODFullHighlight )
- {
- UInt8 mode = LMGetHiliteMode();
- BitClr(&mode,pHiliteBit);
- LMSetHiliteMode(mode);
- InvertRect(&port->portRect);
- }
-
- TextMode(srcXor);
- TextSize(24);
- TextFace(bold + extend);
-
- GetIndString(defaultString, kMenuStringResID, kDefaultContent2ID);
- MoveTo((frameWidth / 2) - (StringWidth(defaultString) / 2),
- (frameHeight / 2) + 6);
- DrawString(defaultString);
-
- SetPenState(&penState);
- RGBForeColor(&foreState);
- RGBBackColor(&backState);
- }
- EndUsingLibraryResources(rfRef);
-
-
- // Restore port chararcteristics.
- SetPort(port);
- port->txSize = size;
- port->txFont = font;
- port->txFace = face;
- */
-
- tsmDraw(ev, &fTERec, facet); //ForTSMTE
- }
-
- //------------------------------------------------------------------------------
- // Method: DrawIconView
- // Origin: SamplePart
- //
- // Description: This method is called by the part when the frame being
- // drawn is in "standard icon" view.
- //
- // The part uses the Icon Utilities toolbox manager to
- // aid in drawing icons in active windows. The Guidelines
- // require a different appearance for selected icons in
- // inactive windows, which we do manually.
- //------------------------------------------------------------------------------
-
- void SamplePart::DrawIconView( Environment* ev,
- ODFacet* facet )
- {
- SOM_Trace("SamplePart","DrawIconView");
-
- Rect iconRect;
- IconTransformType transformType = ttNone;
- CFrameInfo* frameInfo;
- ODFrame* frame;
- ODTypeToken viewType;
-
- frame = facet->GetFrame(ev);
- viewType = frame->GetViewType(ev);
- frameInfo = (CFrameInfo*) frame->GetPartInfo(ev);
-
- // Check to see if the facet is selected
- if ( facet->GetHighlight(ev) == kODFullHighlight )
- transformType = ttSelected;
-
- // Check to see if the frame has been opened into a part window.
- TempODWindow window = frameInfo->AcquirePartWindow(ev);
- if ( window && window->IsShown(ev) )
- transformType |= ttOpen;
-
- // Draw the icon.
- if ( viewType == gGlobals->fLargeIconView )
- SetRect(&iconRect, 0, 0, kODLargeIconSize, kODLargeIconSize);
- else // ( viewType == gGlobals->fSmallIconView )
- SetRect(&iconRect, 0, 0, kODSmallIconSize, kODSmallIconSize);
-
- CUsingLibraryResources res;
- PlotIconID(&iconRect, atAbsoluteCenter, transformType, kBaseResourceID);
- }
-
- //------------------------------------------------------------------------------
- // Method: DrawThumbnailView
- // Origin: SamplePart
- //
- // Description: This method is called by the part when the frame being
- // drawn is in "thumbnail" view.
- //
- // The part uses a picture for its thumbnail view because
- // it has no intrinsic content. A picture resource is
- // probably not sufficient for parts with real content.
- //------------------------------------------------------------------------------
-
- void SamplePart::DrawThumbnailView( Environment* ev,
- ODFacet* facet )
- {
- SOM_Trace("SamplePart","DrawThumbnailView");
-
- // Create or retrieve a cached thumbnail picture.
- PicHandle thumbnail = this->GenerateThumbnail(ev, facet->GetFrame(ev));
-
- Rect bounds = (**thumbnail).picFrame;
- DrawPicture(thumbnail, &bounds);
- }
-
- //------------------------------------------------------------------------------
- // Method: GenerateThumbnail
- // Origin: SamplePart
- //
- // Description: This method is called by the part to generate a thumbnail view
- // from the current content.
- //
- // The part has no content, so we merely load a picture.
- //------------------------------------------------------------------------------
-
- PicHandle SamplePart::GenerateThumbnail( Environment* ev,
- ODFrame* frame )
- {
- SOM_Trace("SamplePart","GenerateThumbnail");
-
- if ( gGlobals->fThumbnail == kODNULL )
- {
- // In cases where a part has been instantiated from scratch and has no
- // content (yet), it is appropriate to display a PICT or some graphic
- // in place of a "real" thumbnail.
-
- LoadThumbnail(ev, &gGlobals->fThumbnail);
-
- // If we were unable to load the PICT resource for whatever reason
- // we will default back to a "frame" view and throw the Resource
- // Manager error as an exception.
- if ( gGlobals->fThumbnail == kODNULL )
- {
- frame->ChangeViewType(ev, gGlobals->fFrameView);
-
- // There is a bug in ResError, when resources are not found,
- // which may cause noErr to be returned. If that is the case,
- // we throw resNotFound.
- THROW_IF_ERROR((ODError)ResError());
- THROW(resNotFound);
- }
- }
-
- return (PicHandle)gGlobals->fThumbnail;
- }
-
- //------------------------------------------------------------------------------
- // Method: GeometryChanged
- // Origin: ODPart
- //
- // Description: This method is called when the ExternalTransform or
- // ClipShape of a facet on one this part's display frames
- // changes.
- //------------------------------------------------------------------------------
-
- void SamplePart::GeometryChanged( Environment* ev,
- ODFacet* facet,
- ODBoolean clipShapeChanged,
- ODBoolean /*externalTransformChanged*/ )
- {
- SOM_Trace("SamplePart","GeometryChanged");
-
- // If clipping changed on the root frame, it means the root frame
- // shaped changed (the window was resized). OpenDoc does not invalidate
- // the area, so we must.
- if ( clipShapeChanged && facet->GetFrame(ev)->IsRoot(ev) )
- facet->Invalidate(ev, kODNULL, kODNULL);
- }
-
- //------------------------------------------------------------------------------
- // Method: HighlightChanged
- // Origin: ODPart
- //
- // Description: This method is called when a facet....
- //------------------------------------------------------------------------------
-
- void SamplePart::HighlightChanged(Environment* ev, ODFacet* facet)
- {
- ODFrame* frame = facet->GetFrame(ev);
-
- // The frame view has no "special" drawing characteristics
- // when opened or selected, so we don't need to update our
- // content.
-
- if ( frame->GetViewType(ev) != gGlobals->fFrameView )
- frame->Invalidate(ev, kODNULL, kODNULL);
- }
-
- //==============================================================================
- #pragma mark • Activation •
- //==============================================================================
-
- //------------------------------------------------------------------------------
- // Method: BeginRelinquishFocus
- // Origin: ODPart
- //
- // Description: This method is called when another part (or possibly
- // ourself) is requesting a focus for one of its display
- // frames. Returning true means we are willing to give
- // up the requested focus.
- //
- // The part willingly gives up any focus unless it is the
- // modal focus which we don't want to give up until we
- // are completely done displaying a modal dialog.
- //------------------------------------------------------------------------------
-
- ODBoolean SamplePart::BeginRelinquishFocus( Environment* ev,
- ODTypeToken focus,
- ODFrame* /*ownerFrame*/,
- ODFrame* proposedFrame )
- {
- SOM_Trace("SamplePart","BeginRelinquishFocus");
-
- ODBoolean willRelinquish = kODTrue;
-
- // Another part is trying to put up a Modal dialog while we
- // are currently displaying ours. Deny the request.
- if ( focus == gGlobals->fModalFocus )
- {
- TempODPart proposedPart = ODAcquirePart(ev,proposedFrame);
- if ( ODObjectsAreEqual(ev, proposedPart, fSelf) == kODFalse )
- willRelinquish = kODFalse;
- }
-
- return willRelinquish;
- }
-
- //------------------------------------------------------------------------------
- // Method: CommitRelinquishFocus
- // Origin: ODPart
- //
- // Description: This method is called when it is actually time to give
- // up a focus that had been requested by another part (or
- // possibly ourself).
- //
- // The part calls its FocusLost method to handle the
- // "reliquishing" of the particular focus.
- //------------------------------------------------------------------------------
-
- void SamplePart::CommitRelinquishFocus( Environment* ev,
- ODTypeToken focus,
- ODFrame* ownerFrame,
- ODFrame* /*proposedFrame*/ )
- {
- SOM_Trace("SamplePart","CommitRelinquishFocus");
-
- // We agreed to give up our FocusSet and now we are being asked to
- // do so.
- this->FocusLost(ev, focus, ownerFrame);
- }
-
- //------------------------------------------------------------------------------
- // Method: AbortRelinquishFocus
- // Origin: ODPart
- //
- // Description: This method is called when another part (or possibly
- // ourself) requested a focus for one of its display
- // frames, but we returned kODFalse from
- // BeginRelinqishFocus for one, or all, of the requested
- // focus. At this point, we are being told to resume
- // ownership of the focus.
- //------------------------------------------------------------------------------
-
- void SamplePart::AbortRelinquishFocus( Environment* ev,
- ODTypeToken /*focus*/,
- ODFrame* /*ownerFrame*/,
- ODFrame* /*proposedFrame*/ )
- {
- SOM_Trace("SamplePart","AbortRelinquishFocus");
-
- // Some parts may have suspended some events in the BeginRelinquishFocus
- // method. If so, they would resume those events here.
- }
-
- //------------------------------------------------------------------------------
- // Method: FocusAcquired
- // Origin: ODPart
- //
- // Description: This method is called when the Arbitrator has
- // registered us as the "owner" of the particular focus.
- // This can occur if we are explicitly assigned a focus, or if a
- // focus is transfered to one of the part's display frames.
- //
- // The part will request its complete focus set to become "active".
- // If the part is successful, we notify ourself to become active.
- //------------------------------------------------------------------------------
-
- void SamplePart::FocusAcquired( Environment* ev,
- ODTypeToken focus,
- ODFrame* ownerFrame )
- {
- SOM_Trace("SamplePart","FocusAcquired");
-
- ODArbitrator* arbitrator = ODGetSession(ev,fSelf)->GetArbitrator(ev);
-
- if ( arbitrator->RequestFocusSet(ev, gGlobals->fUIFocusSet, ownerFrame) )
- {
- this->PartActivated(ev, ownerFrame);
- }
- }
-
- //------------------------------------------------------------------------------
- // Method: FocusLost
- // Origin: ODPart
- //
- // Description: This method is called when the Arbitrator has
- // unregistered us as the "owner" of the particular
- // focus.
- //
- // The part unmarks the active frame if the selection
- // focus is lost.
- //------------------------------------------------------------------------------
-
- void SamplePart::FocusLost( Environment* ev,
- ODTypeToken focus,
- ODFrame* ownerFrame )
- {
- SOM_Trace("SamplePart","FocusLost");
-
- if ( focus == gGlobals->fSelectionFocus )
- {
- CFrameInfo* frameInfo = (CFrameInfo*) ownerFrame->GetPartInfo(ev);
-
- //ForTSMTE
- tsmClose(ev, &fTERec, ownerFrame);
- // ODGetSession(ev,fSelf)->GetDispatcher(ev)->UnregisterIdle(ev, fSelf, ownerFrame);
-
- frameInfo->SetFrameActive(kODFalse);
- }
- }
-
- //------------------------------------------------------------------------------
- // Method: RelinquishAllFoci
- // Origin: SamplePart
- //
- // Description: This method is called when a frame is going away. The method
- // relinquishes all foci the frame owns.
- //------------------------------------------------------------------------------
-
- void SamplePart::RelinquishAllFoci( Environment* ev,
- ODFrame* frame )
- {
- SOM_Trace("SamplePart","RelinquishAllFoci");
-
- ODArbitrator* arbitrator = ODGetSession(ev,fSelf)->GetArbitrator(ev);
-
- TRY
- TempODFrame focusFrame = arbitrator->AcquireFocusOwner(ev, gGlobals->fSelectionFocus);
- if ( ODObjectsAreEqual(ev, focusFrame, frame) )
- {
- arbitrator->RelinquishFocus(ev, gGlobals->fSelectionFocus, frame);
- this->FocusLost(ev, gGlobals->fSelectionFocus, frame);
- }
- CATCH_ALL
- ENDTRY
-
- TRY
- TempODFrame focusFrame = arbitrator->AcquireFocusOwner(ev, gGlobals->fMenuFocus);
- if ( ODObjectsAreEqual(ev, focusFrame, frame) )
- {
- arbitrator->RelinquishFocus(ev, gGlobals->fMenuFocus, frame);
- this->FocusLost(ev, gGlobals->fMenuFocus, frame);
- }
- CATCH_ALL
- ENDTRY
- }
-
- //------------------------------------------------------------------------------
- // Method: PartActivated
- // Origin: SamplePart
- //
- // Description: This method is called when the part has successfully acquired
- // the set of foci which allow it to "run".
- //------------------------------------------------------------------------------
-
- void SamplePart::PartActivated( Environment* ev,
- ODFrame* frame )
- {
- SOM_Trace("SamplePart","PartActivated");
-
- // We are required to re-validate the menubar before displaying it because
- // any part can/could swap the base menubar at any time.
- if ( gGlobals->fMenuBar->IsValid(ev) == kODFalse )
- {
- ODFinalReleaseObject(ev, gGlobals->fMenuBar);
- gGlobals->fMenuBar = ODGetSession(ev,fSelf)->GetWindowState(ev)->CopyBaseMenuBar(ev);
-
- // After copying the "new" base menu bar, don't forget to re-install
- // your part's menus.
- }
-
- // Display our menu bar.
- gGlobals->fMenuBar->Display(ev);
-
- // And set our "active" state.
- CFrameInfo* frameInfo = (CFrameInfo*) frame->GetPartInfo(ev);
- frameInfo->SetFrameActive(kODTrue);
-
- //ForTSMTE
- tsmOpen(ev, &fTERec, frame);
- // ODGetSession(ev,fSelf)->GetDispatcher(ev)->RegisterIdle(ev, fSelf, frame, TEIDLETICKS);
- }
-
- //------------------------------------------------------------------------------
- // Method: ActivateFrame
- // Origin: SamplePart
- //
- // Description: This method is called by the part when a kODEvtMouseUp
- // occurs in an inactive frame in an active window, and
- // when an OpenDoc document comes forward.
- //
- // The part activates the frame by requesting the
- // UIFocusSet (created in Initialize) and by calling
- // FocusAcquired if we were successful. The method
- // returns true if no problems were encountered as a
- // signal to the caller that the frame is now "active".
- //------------------------------------------------------------------------------
-
- ODBoolean SamplePart::ActivateFrame( Environment* ev,
- ODFrame* frame )
- {
- SOM_Trace("SamplePart","ActivateFrame");
-
- ODBoolean activated = kODFalse;
-
- // Request the set of foci necessary to become active.
- if ( ODGetSession(ev,fSelf)->GetArbitrator(ev)
- ->RequestFocusSet(ev, gGlobals->fUIFocusSet, frame) )
- {
- // Activate the part.
- this->PartActivated(ev, frame);
- // We were able to become active.
- activated = kODTrue;
- }
-
- // Let our caller know we succeded or failed.
- return activated;
- }
-
- //------------------------------------------------------------------------------
- // Method: WindowActivating
- // Origin: SamplePart
- //
- // Description: This method is called by the part when a window activation
- // event (kODEvtActivate) occurs.
- //
- // The part remembers the frame's active state and restores it when
- // events come in. If the frame is active and the window is being
- // sent into the background, remember to reactivate the part when
- // the window is reactivated.
- //------------------------------------------------------------------------------
-
- void SamplePart::WindowActivating( Environment* ev,
- ODFrame* frame,
- ODBoolean activating )
- {
- SOM_Trace("SamplePart","WindowActivating");
-
- CFrameInfo* frameInfo = (CFrameInfo*) frame->GetPartInfo(ev);
-
- // The window is being activated and we had the selection focus when
- // the window was deactivated, so activate ourself.
- if ( activating && frameInfo->FrameNeedsReactivating() )
- {
- this->ActivateFrame(ev, frame);
- frameInfo->SetFrameReactivate(kODFalse);
- }
- // The window is being deactivated and we are the active part.
- // Give up our foci and remind ourselves that we need to request
- // the focus when the window is reactivated.
- else if ( !activating && frameInfo->IsFrameActive() )
- {
- //ForTSMTE
- tsmClose(ev, &fTERec, frame);
- // ODGetSession(ev,fSelf)->GetDispatcher(ev)->UnregisterIdle(ev, fSelf, frame);
-
- frameInfo->SetFrameReactivate(kODTrue);
- }
- }
-
- //==============================================================================
- #pragma mark • Event Handling •
- //==============================================================================
-
- //------------------------------------------------------------------------------
- // Method: HandleEvent
- // Origin: ODPart
- //
- // Description: The method is called when an event, which falls into
- // the category of an owned focus, occurs. The two
- // exceptions to this are "mouse movement" events and
- // embedded frame events, which can occur when a part
- // owns no foci.
- //
- // The part returns true if the event was handled.
- //------------------------------------------------------------------------------
-
-
- ODBoolean SamplePart::HandleEvent( Environment* ev,
- ODEventData* event,
- ODFrame* frame,
- ODFacet* facet,
- ODEventInfo* eventInfo )
- {
- SOM_Trace("SamplePart","HandleEvent");
-
- ODBoolean eventHandled = kODFalse;
-
- // Event handling is basically the same as standard Macintosh applications,
- // except that the events have been renamed for cross-platform compatability.
-
- switch ( event->what )
- {
- case kODEvtMouseDown:
- case kODEvtMouseUp:
- eventHandled = this->HandleMouseEvent(ev, event, facet, eventInfo);
- break;
-
- case kODEvtMenu:
- eventHandled = this->HandleMenuEvent(ev, event, frame);
- break;
-
- case kODEvtActivate:
- // We are being notified that a window we are displayed in has
- // just been de/activated (un/hilighted).
- this->WindowActivating(ev, frame, (event->modifiers & activeFlag));
- eventHandled = kODTrue;
- break;
-
- case kODEvtMouseEnter:
- case kODEvtMouseLeave:
- SetCursor(&ODQDGlobals.arrow);
- eventHandled = kODTrue;
- break;
-
- case kODEvtMouseWithin:
- eventHandled = kODTrue;
- break;
-
- //ForTSMTE
- case kODEvtKeyDown:
- case kODEvtAutoKey:
- tsmKey(ev, &fTERec, frame, event);
- eventHandled = kODTrue;
- break;
-
- //ForTSMTE
- case kODEvtNull:
- tsmIdle(ev, &fTERec);
- eventHandled = kODTrue;
- break;
-
- // Other events a part might handle
- // case kODEvtNull:
- case kODEvtMouseDownEmbedded:
- case kODEvtMouseUpEmbedded:
- case kODEvtMouseDownBorder:
- case kODEvtMouseUpBorder:
- case kODEvtWindow:
- // case kODEvtKeyDown:
- // case kODEvtKeyUp:
- // case kODEvtAutoKey:
- case kODEvtOS:
- case kODEvtDisk:
-
- default:
- break;
- }
-
- return eventHandled;
- }
-
- //------------------------------------------------------------------------------
- // Method: AdjustMenus
- // Origin: ODPart
- //
- // Description: This method is called when a kODEvtMouseDown event occurs in the
- // menubar and the part owns the "menu" focus, or when the part is
- // root part of a document.
- //
- // The part first verifies that the base menubar has not been
- // modified, then enables the menu items and changes their names
- // where appropriate (eg. About SamplePart...).
- //------------------------------------------------------------------------------
-
- void SamplePart::AdjustMenus( Environment* ev,
- ODFrame* frame )
- {
- SOM_Trace("SamplePart","AdjustMenus");
-
- // The menubar object always calls the root part's AdjustMenus method before
- // calling the menu focus owner's. Because of this, we need to validate the
- // menubar in the case where we are the root part.
- if ( frame->IsRoot(ev) )
- {
- // We are required to re-validate the menubar before displaying it because
- // any part can/could swap the base menubar at any time.
- if ( gGlobals->fMenuBar->IsValid(ev) == kODFalse )
- {
- ODFinalReleaseObject(ev, gGlobals->fMenuBar);
- gGlobals->fMenuBar = ODGetSession(ev,fSelf)->GetWindowState(ev)->CopyBaseMenuBar(ev);
-
- // After copying the "new" base menu bar, don't forget to re-install
- // your part's menus.
- }
- }
-
- // Enable the "View As Window" command always.
- gGlobals->fMenuBar->EnableCommand(ev, kODCommandViewAsWin, !frame->IsRoot(ev));
-
- // Disable the clipboard commands always
- gGlobals->fMenuBar->EnableCommand(ev, kODCommandCut, kODFalse);
- gGlobals->fMenuBar->EnableCommand(ev, kODCommandPaste, kODFalse);
- gGlobals->fMenuBar->EnableCommand(ev, kODCommandPasteAs, kODFalse);
- gGlobals->fMenuBar->EnableCommand(ev, kODCommandClear, kODFalse);
-
- TRY
- ODArbitrator* arbitrator = ODGetSession(ev,fSelf)->GetArbitrator(ev);
- TempODFrame menuOwner = arbitrator->AcquireFocusOwner(ev, gGlobals->fMenuFocus);
-
- // There is no need to load a resource, create an ODIText object, set the menubar,
- // and cleanup, if we don't own the menu focus.
- if ( ODObjectsAreEqual(ev, frame, menuOwner) )
- {
- Str63 text;
-
- // Get the "about" string from our library's resources.
- // (note: ODGetIndString focuses the resource fork for us)
- ODGetIndString(text, kMenuStringResID, kAboutTextID);
- // Create an IText object to pass into the menubar.
- TempODIText menuItem(CreateIText(gGlobals->fEditorsScript, gGlobals->fEditorsLanguage,
- (StringPtr)&text));
- // Change the "About" menu item text for our part.
- gGlobals->fMenuBar->SetItemString(ev, kODCommandAbout, menuItem);
- }
- CATCH_ALL
- // consume exception
- ENDTRY
- }
-
- //------------------------------------------------------------------------------
- // Method: HandleMenuEvent
- // Origin: SamplePart
- //
- // Description: This method is called by the part when a menu event is
- // received.
- //
- // Using the menu bar object, we determine what the menu
- // command is, and call the appropriate method to handle
- // it.
- //------------------------------------------------------------------------------
-
- ODBoolean SamplePart::HandleMenuEvent( Environment* ev,
- ODEventData* event,
- ODFrame* frame )
- {
- SOM_Trace("SamplePart","HandleMenuEvent");
-
- ODULong menuResult = event->message;
- ODUShort menu = HiWord(menuResult);
- ODUShort item = LoWord(menuResult);
-
- switch ( gGlobals->fMenuBar->GetCommand(ev, menu, item) )
- {
- case kODCommandAbout:
- this->DoDialogBox(ev, frame, kAboutBoxID);
- break;
-
- case kODCommandViewAsWin:
- this->Open(ev, frame);
- break;
-
- // Other commands a part might handle
- case kODCommandOpen:
- case kODCommandInsert:
- case kODCommandPageSetup:
- case kODCommandPrint:
- case kODCommandUndo:
- case kODCommandRedo:
- case kODCommandCut:
- case kODCommandCopy:
- case kODCommandPaste:
- case kODCommandPasteAs:
- case kODCommandClear:
- case kODCommandSelectAll:
- case kODCommandGetPartInfo:
- case kODCommandPreferences:
-
- default:
- return kODFalse;
- }
-
- return kODTrue;
- }
-
- //------------------------------------------------------------------------------
- // Method: HandleMouseEvent
- // Origin: SamplePart
- //
- // Description: This method is called by the part when a mouse event
- // is recieved.
- //
- // A typical part would determine the event type(up/down)
- // and respond appropriately, but we have no "real"
- // content model, so we activate the part as appropriate
- // and call a generic method to handle the event.
- //
- // Remember: When a frame is inactive, the first mouse up event
- // should activate it; inactive frames do not recieve
- // kODEvtMouseDown events.
- //------------------------------------------------------------------------------
-
- ODBoolean SamplePart::HandleMouseEvent( Environment* ev,
- ODEventData* event,
- ODFacet* facet,
- ODEventInfo* eventInfo )
- {
- SOM_Trace("SamplePart","HandleMouseEvent");
-
- // If the facet parameter is invalid, the mouse up occurred outside the
- // bounds of a Modal window, otherwise it should be treated normally.
-
- if ( facet != kODNULL )
- {
- if ( event->what == kODEvtMouseUp )
- {
- ODWindow* window = facet->GetWindow(ev);
-
- TRY
- // Activate inactive windows on the first mouse up event.
- if ( !window->IsActive(ev) )
- window->Select(ev);
- // Activate the frame (if needed) on all subsequent mouse up events.
- else
- {
- ODFrame* frame = facet->GetFrame(ev);
-
- // Get our state information from the PartInfo of the frame.
- CFrameInfo* frameInfo = (CFrameInfo*) frame->GetPartInfo(ev);
-
- // If this frame is not the active one, activate it by requesting
- // the appropriate foci.
-
- if ( !frameInfo->IsFrameActive() )
- {
- if ( this->ActivateFrame(ev, frame) )
- // Keep track of which facet was the last active for positioning
- // child windows.
- frameInfo->SetActiveFacet(facet);
- else
- // We were unable to acquire the necessary focus and activate it.
- return kODFalse;
- }
- }
- CATCH_ALL
- ENDTRY
- }
- else if ( event->what == kODEvtMouseDown )
- {
- Point where;
-
- // Get the localized mouse coordinates from the Event Info.
- where.h = FixedToInt(eventInfo->where.x);
- where.v = FixedToInt(eventInfo->where.y);
-
- // Handle the mouse down event.
- //ForTSMTE
- this->DoMouseEvent(ev, facet, &where, event); // need event record
- // this->DoMouseEvent(ev, facet, &where);
- }
- }
- else
- {
- // User clicked outside the bounds of a Modal window, though we actually
- // never display one.
-
- SysBeep(1);
- }
-
- return kODTrue;
- }
-
- //------------------------------------------------------------------------------
- // Method: DoMouseEvent
- // Origin: SamplePart
- //
- // Description: This method is called by the part to handle mouse
- // events.
- //------------------------------------------------------------------------------
-
- void SamplePart::DoMouseEvent( Environment* ev,
- ODFacet* facet,/*ForTSMTE/*facet*/
- Point* where,/*ForTSMTE/*where*/
- ODEventData* event)/*ForTSMTE*/
- {
- SOM_Trace("SamplePart","DoMouseEvent");
-
- // If you part allows selections or a lasso tool, this is where you
- // would handle those events. This is also where you would handle
- // program controlled buttons or controls.
-
- tsmClick(ev, &fTERec, facet, where, event); //ForTSMTE
- }
-
- //------------------------------------------------------------------------------
- // Method: DoDialogBox
- // Origin: SamplePart
- //
- // Description: This method is called by the part when a dialog needs to be
- // displayed (eg. the About Box). If a valid error number is passed
- // in, an error dialog will be displayed.
- //------------------------------------------------------------------------------
-
- void SamplePart::DoDialogBox( Environment* ev,
- ODFrame* frame,
- ODSShort dialogID,
- ODUShort errorNumber )
- {
- SOM_Trace("SamplePart","DoDialogBox");
-
- ODFrame* focusFrame = frame;
- ODSession* session = ODGetSession(ev,fSelf);
-
- // If the calling method does not have a frame available to it, we need to
- // locate a frame to use for requesting the modal focus. Find the first valid
- // frame in our display frames list.
- if ( focusFrame == kODNULL )
- {
- CListIterator fiter(fDisplayFrames);
- for ( CFrameProxy* proxy = (CFrameProxy*) fiter.First();
- fiter.IsNotComplete(); proxy = (CFrameProxy*) fiter.Next() )
- {
- if ( proxy->FrameIsLoaded(ev) )
- focusFrame = proxy->GetFrame(ev);
- if ( focusFrame ) break;
- }
- }
-
- // Our dialog boxes are modal so we must request the Modal focus to prevent
- // multiple modal dialogs being displayed simultaneously.
-
- TempFocus modalFocus(ev, gGlobals->fModalFocus, focusFrame);
- if ( modalFocus.Request() )
- {
- ODSShort itemHit;
-
- // Dim the frontmost document window.
- session->GetWindowState(ev)->DeactivateFrontWindows(ev);
-
- CUsingLibraryResources res;
-
- DialogPtr dialog = ODGetNewDialog(ev, dialogID, session, kODTrue);
-
- if ( dialog )
- {
- if ( errorNumber > 0 )
- {
- Handle itemHandle;
- Rect itemRect;
- short itemType;
- Str255 errStr;
-
- GetIndString(errStr, kErrorStringResID, errorNumber);
- GetDialogItem(dialog, kErrStrFieldID, &itemType, &itemHandle, &itemRect);
- SetDialogItemText(itemHandle, errStr);
-
- // We don't need the cancel button for an error dialog.
- HideDialogItem(dialog, cancel);
- }
-
- SetCursor(&ODQDGlobals.arrow);
- ShowWindow(dialog);
- ModalDialog(kODNULL, &itemHit);
- DisposeDialog(dialog);
- }
- else
- {
- // Could not load About box dialog... something is amiss.
- SysBeep(2);
- }
-
- // Hilite the frontmost document window.
- session->GetWindowState(ev)->ActivateFrontWindows(ev);
- }
- else
- {
- // If we can't get the modal focus, then another modal dialog is
- // already being displayed.
- SysBeep(2);
- }
- }
-
-